如何在没有数学库的情况下截断JavaScript中的小数? [英] How to truncate decimals in JavaScript without Math library?

查看:62
本文介绍了如何在没有数学库的情况下截断JavaScript中的小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要数字只能有2个小数点(如货币形式),而我使用的是:

I need numbers to have only 2 decimals (as in money), and I was using this:

Number(parseFloat(Math.trunc(amount_to_truncate * 100) / 100));

但是我不再支持数学库.

But I can no longer support the Math library.

在没有数学库的情况下又如何不舍入小数位怎么办?

How can I achieve this without the Math library AND withou rounding the decimals?

推荐答案

简单化

const trunc = (n, decimalPlaces) => {
  const decimals = decimalPlaces ? decimalPlaces : 2;
  const asString = n.toString();
  const pos = asString.indexOf('.') != -1 ? asString.indexOf('.') + decimals + 1 : asString.length;
  return parseFloat(n.toString().substring(0, pos));
};

console.log(trunc(3.14159265359));
console.log(trunc(11.1111111));
console.log(trunc(3));
console.log(trunc(11));
console.log(trunc(3.1));
console.log(trunc(11.1));
console.log(trunc(3.14));
console.log(trunc(11.11));
console.log(trunc(3.141));
console.log(trunc(11.111));

这篇关于如何在没有数学库的情况下截断JavaScript中的小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆