简体   繁体   中英

Truncate float (not rounded) to 2 decimal places

Please, I need convert String into Float or Double in 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.

// 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. It's a String with value 1

It's possible to convert string into decimal number with 2 fixed places without rounding?

If you're interested about simple spent manager, I'm programmit it here 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.

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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