> 文档中心 > 如何将页面上的数字显示为千分符且保留两位小数?toLocaleString()和toFixed(2)混用无效

如何将页面上的数字显示为千分符且保留两位小数?toLocaleString()和toFixed(2)混用无效

如何将页面上的数字显示为千分符且保留两位小数?toLocaleString()和toFixed(2)混用无效

近日突然发现页面数值列显示改为千分符格式的方法toLocaleString()前后端用起来都有坑,特此记录一下细节。

前端javascript实现

  1. 问题复现
// 单独用toFixed(2)和toLocaleString() 正常let price = 1234price.toFixed(2) //1234.00Number(totalValue).toLocaleString() //1,234price = 1234.12price.toFixed(2)// 1234.12Number(price).toLocaleString() //1,234.12// 合并使用不行parseFloat(price).toFixed(2).toLocaleString() //1234.12parseFloat((11234).toFixed(2)).toLocaleString() //1,234
  1. 解释:
    一旦你使用toFixed,price是一个字符串,而不是一个数字,所以toLocaleString不会改变它。
  2. 正确的用法,用toLocaleString()自带的options参数设置代替toFixed():
let price = 1234.12price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })   //1,234.12

最后我抽取了一个公共方法:

var numberToPrice = function(number) { if (typeof number !== 'number') { return 'NaN'; } //这里Math.floor是保留两位时防止产生四舍五入,toFixed()默认会进行四舍五入let price = Math.floor(100 * number) / 100;  let newPrice = price.toLocaleString('en-US', {  //'en-US'参数指定区域,此参数可以直接用undefinedminimumFractionDigits: 2, maximumFractionDigits: 2 }) return newPrice; } console.log(numberToPrice(13422.126))  // 13422.12

后端Java实现

机智的我也想到了从后端格式化数据的方法,那大前端就省事多了,也得注意这个点:
Java种的toLocaleString()方法已经过时我的后端用不了(也可能缺少某个jar懒得加了)
用DecimalFormat来格式化,我的页面数据既有整数也有小数没有统一格式,为了不影响原先的展示效果只增加了千分符,公共方法如下:

// 千分符 格式化    public static String parseNumberQff(String pattern, String number) throws Exception { BigDecimal data = new BigDecimal(number); if (StringUtils.isNotEmpty(pattern)){     DecimalFormat df = new DecimalFormat(pattern);     return df.format(data); } if (StringUtils.isNotEmpty(number) && number.indexOf(".") > 0){     pattern = ",###,###.00"; } else {     pattern = ",###,###"; } DecimalFormat df = new DecimalFormat(pattern); return df.format(data);    }

测试OK

在这里插入图片描述