HarmonyOS NEXT实战:千分分隔符工具
##HarmonyOS Next实战##HarmonyOS SDK应用服务##教育##
目标:实现千分分隔符工具封装
NumberFormat 创建数字格式化对象
constructor(locale: string | Array<string>, options?: NumberOptions)
locale:表示区域信息的字符串,由语言、脚本、国家或地区组成。 options:创建数字格式化对象时可设置的配置项。 示例
// 使用 en-GB locale创建NumberFormat对象,style设置为decimal,notation设置为scientific
let numfmt = new intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"});
接口
format(number: number): string//格式化数字字符串。
resolvedOptions(): NumberOptions//获取创建数字格式化对象时设置的配置项。
NumberOptions:创建数字格式化对象时设置的配置项。
- locale:区域参数, 如:"zh-Hans-CN"。locale属性默认值为系统当前Locale。
- currency:货币单位, 取值符合ISO-4217标准,如:"EUR","CNY","USD"等。
- currencySign:货币单位的符号显示,取值包括: "standard","accounting"。默认值为standard。
- currencyDisplay:货币的显示方式,取值包括:"symbol", "narrowSymbol", "code", "name"。默认值为symbol。
- unit:单位名称,如:"meter","inch",“hectare”等。
- unitDisplay:单位的显示格式,取值包括:"long", "short", "narrow"。默认值为short。
- unitUsage:单位的使用场景,默认值为default。
- signDisplay:数字符号的显示格式,取值包括:"auto":自动判断是否显示正负符号;"never":不显示正负号;"always":总是显示正负号;"exceptZero":除了0都显示正负号。默认值为auto。
- compactDisplay:紧凑型的显示格式,取值包括:"long", "short"。默认值为short。
- notation:数字的格式化规格,取值包括:"standard", "scientific", "engineering", "compact"。默认值为standard。
实战
export class NumberKit {
/**
* 千位分隔符格式化金钱,并只保留两位小数
* @param money
* @returns
*/
static formatMoney(money: number): string {
/**
* 创建一个 Intl.NumberFormat 对象,指定语言和选项
* 用途:格式化数字为英文风格的金融数字,千分分隔符,
*/
const formatter = new Intl.NumberFormat('en-US', {
style: 'decimal', // 使用十进制风格
minimumFractionDigits: 2, // 最小小数位数
maximumFractionDigits: 2, // 最大小数位数
useGrouping: true // 启用分组(即每三位用逗号分隔)
});
return formatter.format(money)
}
/**
* 千位分隔符,小数不变
* ###待完善:根据数字小数位数,保留全部位数
* @param num
* @returns
*/
static thousandsSeparator(num: number) {
const formatter = new Intl.NumberFormat('en-US', {
// style: 'decimal', // 使用十进制风格
minimumFractionDigits: 9, // 最小小数位数
maximumFractionDigits: 9, // 最大小数位数
useGrouping: true // 启用分组(即每三位用逗号分隔)
});
return formatter.format(num)
}
/**
* 判断是否是数值
* @param value
*/
static processNumber(value: number | string) {
if (typeof value === "number") {
console.log(value.toFixed(2));
} else {
console.log("Not a number");
}
}
}
使用
@Entry
@Component
struct Index {
@State message: string = '千分分隔符';
build() {
Column() {
Text(this.message)
.id('HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
Text(NumberKit.formatMoney(456781.2365))
Text(NumberKit.thousandsSeparator(456781.2365))
}
.height('100%')
.width('100%')
}
}