1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import type common from '@ohos.app.ability.common'; 17import { DeviceUtils } from '../util/DeviceUtils'; 18 19/** 20 * 格式化工具 21 * 22 * @since 2022-06-06 23 */ 24export namespace FormatUtils { 25 const DECIMAL_POINT = 2; 26 27 /** 28 * 格式化文件大小 29 * 30 * @param bytes 文件大小 31 * @param decimalPoint 精确到小数点后两位 32 * @return 格式化后的字符串 33 */ 34 export function formatFileSize(bytes: number, decimalPoint = DECIMAL_POINT): string { 35 if (bytes <= 0) { 36 return '0 Bytes'; 37 } 38 const MAX_BYTES: number = 1024 * 1024 * 1024; 39 const DOWN_POINT: number = 0; 40 const UP_POINT: number = 5; 41 const ONE_KB = 1024; 42 let data: number = Math.min(bytes, MAX_BYTES); 43 let point: number = Math.min(Math.max(decimalPoint, DOWN_POINT), UP_POINT); 44 let sizes = ['Bytes', 'KB', 'MB', 'GB']; 45 let index = Math.floor(Math.log(data) / Math.log(ONE_KB)); 46 return parseFloat((bytes / Math.pow(ONE_KB, index)).toFixed(point)) + ' ' + sizes[index]; 47 } 48 49 /** 50 * 格式化字符串 51 * 52 * @param 待格式化的字符串 53 * @param args 待匹配的内容 54 * @return 格式化后的字符串 55 */ 56 export function formatStr(message: string, ...args: (string | number)[]): string { 57 if (!message) { 58 return ''; 59 } 60 const PLACE_HOLDER = new RegExp('%s|%d|%[0-9]\\$s'); 61 let segments = message.split(PLACE_HOLDER); 62 let formattedStr: string = ''; 63 for (let i = 0; i < segments.length; i++) { 64 formattedStr += segments[i]; 65 if (i !== segments.length - 1) { 66 formattedStr += args[i] ? args[i] : ''; 67 } 68 } 69 return formattedStr; 70 } 71 72 /** 73 * 字符串或字符串资源转大写 74 * 75 * @param context 上下文 76 * @param text 待格式化的字符串 77 * @param args 待匹配的内容 78 * @return 转大写后的字符串 79 */ 80 export function toUpperCase(context: common.Context, text: ResourceStr, ...args: (string | number)[]): string { 81 if (!text) { 82 return ''; 83 } 84 if (typeof text === 'string') { 85 return text.toUpperCase(); 86 } else { 87 let message: string = context?.resourceManager.getStringSync(text.id); 88 return formatStr(message, ...args).toUpperCase(); 89 } 90 } 91 92 /** 93 * 数字格式化 94 * 95 * @param num 待格式化数字 96 * @return 格式化之后的数字 97 */ 98 export function getNumberFormat(num: number): string { 99 let language: string = DeviceUtils.getSystemLanguage(); 100 let numfmt: Intl.NumberFormat = new Intl.NumberFormat(language, {style:'percent', notation:'standard'}); 101 return numfmt.format(num); 102 } 103}