简体   繁体   English

将浮点数(不四舍五入)截断到小数点后 2 位

[英]Truncate float (not rounded) to 2 decimal places

Please, I need convert String into Float or Double in Javascript.请,我需要在 Javascript 中将字符串转换为浮点数精度数。 But I don't want it round it.但我不希望它围绕它。 I want just fixed 2 decimal places Number which means input 0.996 return me 0.99 and not 1.我只想固定 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 );

After this, total is not a number anymore.在此之后, total不再是一个数字。 It's a String with value 1这是一个值为 1 的字符串

It's possible to convert string into decimal number with 2 fixed places without rounding?可以将字符串转换为具有 2 个固定位置而不四舍五入的十进制数吗?

If you're interested about simple spent manager, I'm programmit it here https://codepen.io/littleTheRabbit/pen/JjYWjRG如果您对简单的花费管理器感兴趣,我在这里编程https://codepen.io/littleTheRabbit/pen/JjYWjRG

Thank you very much for any advice非常感谢您的任何建议

Best Regards此致

This can be done by dropping the extra digits you don't want by using multiplication and division.这可以通过使用乘法和除法删除不需要的额外数字来完成。 For example, if you want 0.994 to be 0.99, you can multiply by 100 (to cover 2 decimal places), then truncate the number, and then divide it back by 100 to it to the original decimal place.例如,如果您希望 0.994 为 0.99,您可以乘以 100(以覆盖 2 个小数位),然后将数字截断,然后将其除以 100 到原来的小数位。

example:例子:

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

So here is a function that will do that:所以这里有一个 function 可以做到这一点:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM