0

I am working on React project.

I have use case where I have to add step attribute on Number <Input> tag. This step attribute will be dynamic. Based on array data.

Array data is [{ precision: 2 }, { precision: 4 }, { precision: 5 }].

So I generate the step like:

<input type="number" step={ 10 ** -precision } >

Here 10 ** -precision will output :

0.01 for precision = 2

0.0001 for precision = 4

0.00001 fror precision = 5

This is what I want, and it is working fine in Firefox and Opera.

But Chrome is the issue, Chrome's output for 10 ** -4 is 0.00009999999999999999. Which is breaking in my case.

Chrome's output is correct till 10 ** -3 after that it is printing wrong.

enter image description here

My chrome version is : 74.0.3729.131 and OS: MacOs Mojave: 10.14.4

Rahul Sagore
  • 1,588
  • 2
  • 26
  • 47
  • Using chrome, I get .0001 from 10 ** -4; perhaps you could just try Math.round(var);? – shadow2020 May 10 '19 at 15:39
  • @Amy Not duplicate. That is not related to JS specifically. Every programming language output `0.1 + 0.2 -> 0.30000000000000004` – Rahul Sagore May 10 '19 at 15:42
  • @shadoe2020 what is your chrome version? Mine is `74.0.3729.131` – Rahul Sagore May 10 '19 at 15:43
  • 73.0.3683.103 (Official Build) (64-bit) – shadow2020 May 10 '19 at 15:49
  • @RahulSagore It doesn't need to be JS-specific to be a duplicate, considering that everything running on a computer follows the same IEEE-754 rules. It does explain why this happens in JS. –  May 10 '19 at 15:52
  • @Amy Firefox and Opera calculating negative exponent correctly, Not on Chrome. While `0.1 + 0.2` is calculating `0.30000000000000004` everywhere, it's known. This is chrome specific issue, on latest version. – Rahul Sagore May 10 '19 at 15:55
  • @JoshLee Thanks, that is the correct duplicate. I could not find that question. – Rahul Sagore May 10 '19 at 15:56
  • 1
    [Floating-Point Questions Are Endless on stackoverflow.com](https://www.exploringbinary.com/floating-point-questions-are-endless-on-stackoverflow-com/) – Thomas May 10 '19 at 16:05

1 Answers1

1

Maybe it's a floating point precision issue. If you only have to pass it as prop to the tag you can try <input type="number" step={ (10 ** -precision).toFixed(precision) } />

Trio
  • 78
  • 7
  • Yeah this is possible solution. Will check and upvote. But the issue is really weird. Firefox and Opera outputting perfectly – Rahul Sagore May 10 '19 at 15:50
  • I agree it's weird (also chromium works fine), and i cant quite explain it (js engine implementation? i dont know what to say). Let me know if the ```toFixed``` trick works – Trio May 10 '19 at 15:54