将浮点数(未舍入)截断到小数点后两位

时间:2020-04-25 15:42:50

标签: javascript floating-point rounding

请,我需要在Javascript中将 String 转换为 Float Double 。但是我不想把它弄糟。我只想固定2个小数位数字,这意味着输入 0.996 返回我 0.99 而不是1。

// 1. Convert number to float strip to 2 decimal places
var total = ',996' // (or 0.996 if you want, doesn't matter)
total = Math.round(parseFloat(
                   total.replace (',', '.')
)).toFixed(2);

console.log ( typeof total );
console.log ( total );

此后,total不再是数字。这是一个值为1的字符串

是否可以将字符串转换为带有2个固定位的十进制数而无需舍入?

如果您对简单的支出管理者感兴趣,请在此处进行编程 https://codepen.io/littleTheRabbit/pen/JjYWjRG

非常感谢您的任何建议

最好的问候

1 个答案:

答案 0 :(得分:1)

这可以通过使用乘法和除法删除不需要的多余数字来完成。例如,如果您希望0.994为0.99,则可以乘以100(以覆盖2个小数位),然后截断该数字,然后再除以100再除以原始的小数位。

示例:

  0.994 * 100 = 99.4
  99.4 truncated = 99.0
  99.0 / 100 = 0.99

所以这是一个可以做到这一点的函数:

const truncateByDecimalPlace = (value, numDecimalPlaces) =>
  Math.trunc(value * Math.pow(10, numDecimalPlaces)) / Math.pow(10, numDecimalPlaces)

console.log(truncateByDecimalPlace(0.996, 2)) // 0.99