通过math.js解决科学计数法保留两位小数的问题。

通过math.js解决科学计数法保留两位小数的问题。

问题:
整数超过6位数的数值为字符串类型时会自动转换为科学计数法,采用字符串截取两位小数出错。例如:2.44533610979e+5截取完理想值为:2.44533e+5;实际结果为:2.44。
思路:

  1. 先把大数值转换为Number类型,再采用字符串截取两位小数,报错。不可取!!
  2. 先把大数值转换为Number类型,再采用Math.floor截取两位小数,正常;但是特殊情况有问题。例如:4.528截取完理想值为4.52;实际结果为:4.51。

正确的思路做法:
①必须在项目先安装配置math.js。

		var prive = 2445.33610979;
		price = this.$math.multiply(this.$math.bignumber(Number(price)),100);
		console.log(price);//2.44533610979e+5
        price = this.$math.floor(Number(price));
		console.log(price);//2.44533e+5
        price = this.$math.divide(this.$math.bignumber(Number(price)),100);
		console.log(price);//2445.33

要注意的是第四行代码的math.floor是math.js的,不是JavaScript的。
备注:正确安装配置math.js可以参照上上篇博客,链接为:https://blog.csdn.net/weixin_42857055/article/details/103823586

----------------------------------------分割线----------------------------------------
补充:
字符串截取两位小数的方法:

strNumber= strNumber.replace(/([0-9]+.[0-9]{2})[0-9]*/,"$1");

你可能感兴趣的:(通过math.js解决科学计数法保留两位小数的问题。)