3

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

user2864740
  • 60,010
  • 15
  • 145
  • 220
Bambi Bunny
  • 1,008
  • 2
  • 9
  • 18

1 Answers1

3

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
Rob Brander
  • 3,702
  • 1
  • 20
  • 33