这个问题的灵感来自线上一个小bug,前两天刚看完同事写的代码,对数字类型处理的很好,之前一直都是用正则和toFixed(2)
处理数字相关,后面发现使用numeral.js
处理更完美。
0.1+0.2=0.30000000000000004
0.14*100=14.000000000000002
9999999--->'9,999,999'
1234567890--->1,234,567,890
0.1+0.2的精准算法,这里以
加法举例了,换成减、乘、除法都是一样的
const sum = 0.1 + 0.2; // 0.14 * 100; 乘法
const roundedSum = parseFloat(sum.toFixed(10));
console.log(roundedSum); // 输出 0.3
const sum = parseFloat((0.1 + 0.2).toFixed(10));
console.log(sum); // 输出 0.3
const sum = Math.round((0.1 + 0.2) * 1e10) / 1e10;
console.log(sum); // 输出 0.3
const sum = 0.1 + 0.2;
const roundedSum = Math.abs(sum - 0.3) < Number.EPSILON ? 0.3 : sum;
console.log(roundedSum); // 输出 0.3
// 安装
npm i numeral -S
// 挂原型链上
import numeral from 'numeral'
Vue.prototype.$numeral = numeral; // 数字金额
let num = this.$numeral(14*100).format('0,0.00')
console.log(num); // 输出 14.00
toLocaleString()
js内置的方法处理,这个方法最简单var num = 9999999;
console.log(num.toLocaleString()) // 9,999,999
function addThousandSeparator(number) {
// 将数字转换为字符串
const numberString = String(number);
// 使用正则表达式添加千位符
const formattedNumber = numberString.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return formattedNumber;
}
const result = addThousandSeparator(9999999);
console.log(result); // 输出 '9,999,999'
\B(?=(\d{3})+(?!\d))
是一个正则表达式模式,它使用正向零宽断言来匹配不在数字之前的位置,但是在每三个数字之间。这样就可以在这些位置插入千位符
Numeral.js
处理
<script src="https://cdn.bootcss.com/numeral.js/2.0.6/numeral.min.js"></script>
var formattedNumber = numeral(9999999).format('0,0'); // 输出:9,999,999
console.log('formattedNumber',formattedNumber);
这里注意括号里逗号与小数点的区别format('0,0.00')
<script src="https://cdn.bootcss.com/numeral.js/2.0.6/numeral.min.js"></script>
var formattedNumber = numeral(9999999.56841).format('0,0.00'); // 输出:9,999,999
console.log('formattedNumber',formattedNumber);
<script src="https://cdn.bootcss.com/numeral.js/2.0.6/numeral.min.js"></script>
<script>
var string = numeral(1634600).format('0,0');
console.log(string)
// 乘法运算
var result = numeral(0.14).multiply(100).value(); // 输出:6
console.log('result',result);
var result1 = numeral(0.14*100).value();
console.log('result1',result1,numeral(0.14*100).format('0,0.00'));
// this.$numeral(0.14*100).format('0,0.00')
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>numeral.js</title>
</head>
<body>
numeral.js
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/numeral.js/2.0.6/locales.min.js"></script> -->
<script src="https://cdn.bootcss.com/numeral.js/2.0.6/numeral.min.js"></script>
<script>
var string = numeral(1634600).format('0,0');
console.log(string)
// 乘法运算
var result = numeral(0.14).multiply(100).value(); // 输出:6
console.log('result',result);
var result1 = numeral(0.14*100).value();
console.log('result1',result1,numeral(0.14*100).format('0,0.00'));
// this.$numeral(0.14*100).format('0,0.00')
</script>
</body>
</html>