目录
decimal.js使用场景
decimal.js介绍
decimal.js使用
1、安装依赖
2、引入并使用
decimal.js函数封装
decimal.js使用场景- js有精度问题, 对于一些金额的计算就总是与偶莫名其妙的问题。
- decimal.js是使用的二进制来计算的, 所以能解决js的精度问题。
整数和浮点数 简单但功能齐全的API 复制许多JavaScript Number.prototype和Math对象的方法 还处理十六进制,二进制和八进制值 比Java的BigDecimal的 JavaScript版本更快,更小,甚至更容易使用 没有依赖 广泛的平台兼容性:仅使用JavaScript 1.5(ECMAScript 3)功能 全面的文档和测试集 包括一个TypeScript声明文件:decimal.d.ts
npm install --save decimal.js
2、引入并使用
import { Decimal } from 'decimal.js'
const a = 2.998;
const b = 8.035;
// 加法
let c = new Decimal(a).add(new Decimal(b))
// 减法
let d = new Decimal(a).sub(new Decimal(b))
// 乘法
let e = new Decimal(a).mul(new Decimal(b))
// 除法
let f = new Decimal(a).div(new Decimal(b))
decimal.js函数封装
/*
参数介绍
money:金额
fixed:保留小数点的位数
*/
function handleFormatFixed(money, fixed) {
// console.log(money);
try {
if (money > 0) {
money = new Decimal(money).div(new Decimal(1000000000000));
//var money = money/1000000000000;
if (fixed != undefined) {
money = money.toFixed(fixed);
}
return handleFormat(money);
} else {
return 0;
}
} catch (e) {
//console.log(e);
}
}
/*
千分位显示函数封装
*/
function handleFormat(num) {
const arr = num.toString().split('.');
const str =
(arr[0] || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,') +
(arr[1] ? '.' + arr[1] : '');
return handleCutZero(str);
}
/*
去除小数位后面对于的0
*/
function handleCutZero(num) {
let newstr = num;
// console.log(num.indexOf('.') - 1);
let leng = num.length - num.indexOf('.') - 1;
if (num.indexOf('.') > -1) {
for (let i = leng; i > 0; i--) {
if (
newstr.lastIndexOf('0') > -1 &&
newstr.substr(newstr.length - 1, 1) == 0
) {
let k = newstr.lastIndexOf('0');
if (newstr.charAt(k - 1) == '.') {
return newstr.substring(0, k - 1);
} else {
newstr = newstr.substring(0, k);
}
} else {
return newstr;
}
}
}
return num;
}