JS中对decimal类型数据的处理(高精度计算)

介绍

Decimal为SQL Server、MySql等数据库的一种数据类型,不属于浮点数类型,可以在定义时划定整数部分以及小数部分的位数。使用精确小数类型不仅能够保证数据计算更为精确,还可以节省储存空间

引入文件

有关npm指令参考

/**  Node.js  */

$ npm install --save decimal.js
var Decimal = require('decimal.js');

/** ES6 模块方式 */

import { Decimal } from 'decimal.js';//刚刚加入时IDEA可能还没反应所以显示灰色,过会就好了

使用

//加法运算
var a = 0.13;
var b = 0.25;
console.log('加法运算 a + b =', a + b);
console.log('使用Decimaljs a + b =', new Decimal(a).add(new Decimal(b)).toNumber());

//减法
var a = 1.0;
var b = 0.99
console.log('直接减法运算 a - b =', a - b);
console.log('使用Decimaljs a - b =', new Decimal(a).sub(new Decimal(b)).toNumber().toFixed(2);//保留两位数据

//乘法
var a = 1.01;
var b = 1.02;
console.log('直接乘法运算 a * b =', a * b);
console.log('使用Decimaljs a * b =', new Decimal(a).mul(new Decimal(b)).toNumber());

//除法
var a = 0.033;
var b = 10;
console.log('直接除法运算 a / b =', a / b);
console.log('使用Decimaljs a / b =', new Decimal(a).div(new Decimal(b)).toNumber());

猜你喜欢

转载自blog.csdn.net/qq_28202661/article/details/90766418
今日推荐