Phil Mok
Phil Mok

Reputation: 4050

React Native Slider updates incorrect step value

I am building a React Native app which uses a few Sliders. For some reason, the slider is incapable of producing decimal values that are not multiples of 0.25. As I move the slider, I set the state of the component and display the slider's value.

For example, I have a slider that ranges from 0 to 1 with a step of 0.01. When the slider tracker is in the middle of the range, it sets the component's state to 0.5. If I move the tracker up one step, it should set the state to 0.51, but instead it goes to 0.5099999904632568.

Even if I increase the step to 0.1, this error still occurs. I know I could simply round these values before displaying them to the user, but does anybody know why this happens? Is it because of floating point math?

enter image description here

Upvotes: 1

Views: 3124

Answers (2)

I had the same issue as I need from 34 to 42 with a step of 0.1 My solution was to give min=340 max=420 step=1 and the place I'm showing the value I'm dividing by 10 and it works fine without the need of rounding up.

Upvotes: 3

shamsup
shamsup

Reputation: 2032

The issue isn't necessarily floating point math. It's just floating point numbers (stored as binary) in general.

There's a really good explanation to the problem in this answer, but here's a quick summary: just like decimal (base 10) notation has trouble representing fractions like 1/3, where it represents them as a repeating sequence (ie 0.3333333... repeating). Binary has this same problem with numbers that are represented just fine in decimal, like 0.1 (which is something like 0.0001100110011... in binary). This difference then gets amplified by the number of operations you do using the number.

One approach you could take, at least for displaying these numbers, is rounding, like you said. However, this won't eliminate other inaccuracies due to the floating point numbers in your code.

Hope this helps!

Upvotes: 1

Related Questions