0

is there a way to have 2 numbers after comma without rounding the value. I want the exact value. Math.round() and toFixed() give the value rounded.

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
mariem_11
  • 81
  • 2
  • 6
  • Does this answer your question? [javascript - how to prevent toFixed from rounding off decimal numbers](https://stackoverflow.com/questions/10808671/javascript-how-to-prevent-tofixed-from-rounding-off-decimal-numbers) – Abhishek Bhagate May 27 '20 at 11:35

2 Answers2

0

You can do the workaround with help of Math.ceil() and Math.floor() functions. Another way, is treat is as an string and use .slice()

i.e:

number = number.slice(0, number.indexOf(".")+3); //this should give you 2 decimals
Number(number); //Convert it to "Number" again, so you can operate with it
marques
  • 29
  • 4
0

Solution without type conversions


While solving the issue, you should bear in mind that bouncing back and forth between data types may cost you some of app performance wasted

Instead, I'd suggest to modify input number directly:

  • shift the dot n positions to the right by multiplying your number by 10 in power of n (10**n)
  • cut off what's left after dot, using bitwise OR (|) that implicitly turns the float into integer
  • divide the result by 10 in power of n to shift the dot n positions back to the left

Following is a quick live-demo:

const num = 3.14159265,
      precision = 4,
      
      limitPrecision = (n,p) => (0|n*10**p)/10**p
      
console.log(limitPrecision(num, precision))
.as-console-wrapper{min-height:100%;}
Community
  • 1
  • 1
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42