2

I am learning React Native. Made 1 2 apps. Now in my third app I need to make some arithmetic operations. It is very simple. Like 100 * 4.31 and 100 * 4.41

console.log(100 * 4.31)
console.log(100 * 4.41)

Output

430.99999999999994
441

Out put should be 4.31 in first log but it is not.

Can anyone find me a solution what is wrong with this simple arithmetic operation in React Native?

5eb
  • 14,798
  • 5
  • 21
  • 65
Dharmik
  • 2,325
  • 3
  • 27
  • 37
  • 2
    It's not react native problem. check [this](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Pooya Haratian Jul 25 '20 at 07:41

1 Answers1

1

You have to use toFixed() function for rounding off the result of arithmetic expressions like this

console.log(Number((100 * 4.31).toFixed(2)));

console.log(Number((100 * 4.41).toFixed(2)));

Anyway its just a JavaScript simple problem, not a specific of React Native.

DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
  • Yes, I have tested this in JavaScript after you mention in your answer. But why it is still there I mean isn't this big issue for some of calculations? Curious to know.. – Dharmik Jul 26 '20 at 12:50
  • Basically its the result of calculation which you will get from a scientific calculator. So, in reality it's not a problem but the correct result of calculation. What you want to do is limiting the result to a limited number of digits. – DevLoverUmar Jul 26 '20 at 17:40