0

Using the parseFloat method converted the string value from the DB to float and multiplied by 100. But the output looks odd. Following the piece of code which I've used.

parseFloat(upliftPer) * 100 //upliftPer value read from DB and its value is 0.0099

So when it multiplied with 100 getting 0.9900000000000001 I suppose to get 0.99 but some junk values getting appended. Also I went ahead and did the same in the console log of chrome browser still the same result. I have attached screenshots for reference. Solution I needed is 0.0099 * 100 should result 0.99. I cant apply round / toFixed since I need more precision.

enter image description here

georgeawg
  • 48,608
  • 13
  • 72
  • 95
LokiDil
  • 197
  • 1
  • 3
  • 13

2 Answers2

0

This is because of JavaScript internal casting to double type. There's always a certain degree of noise due to floating point inaccuracy. Here's some information on that.

You can just round it up using toFixed(x) with as much decimal spaces of precision as you want (or as much as JavaScript would allow you).

sebasaenz
  • 1,917
  • 2
  • 20
  • 25
0

It is not related to JavaScript nor to any programming language.

It’s because of the conversion from decimal floating-point to binary representation: the process ends up in an infinite process that has to be truncated because of the limited number of bits available for storing the numbers (and thus, of the limited amount of memory in computers)

Check out the process of conversion and take a look at this converter that tells you how much error there is during conversion

As @sebasaenz pointed out in his answer, you can use toFixed(x) to round up your number and get rid of junk

Matteo Meil
  • 1,192
  • 10
  • 20