js计算大额数据当中丢失精度以及消除科学计数法解决方案—decimal.js的使用

目录

decimal.js使用场景

decimal.js介绍

decimal.js使用

1、安装依赖

2、引入并使用

 decimal.js函数封装


decimal.js使用场景

  1. js有精度问题, 对于一些金额的计算就总是与偶莫名其妙的问题。
  2. decimal.js是使用的二进制来计算的, 所以能解决js的精度问题。

decimal.js介绍


整数和浮点数 简单但功能齐全的API 复制许多JavaScript
Number.prototype和Math对象的方法
还处理十六进制,二进制和八进制值 比Java的BigDecimal的 JavaScript版本更快,更小,甚至更容易使用 没有依赖
广泛的平台兼容性:仅使用JavaScript 1.5(ECMAScript 3)功能 全面的文档和测试集
包括一个TypeScript声明文件:decimal.d.ts

decimal.js API

decimal.js使用


1、安装依赖

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;
}

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任磊abc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值