首页 > 数据库 > 数据库开发技术 > 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:创建数字格式化对象时设置的配置项。
实战
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%')
}
}
原文作者:;如有侵权,请联系管理员删除。