I just need to round a float to one decimal point but nothing is working. The most common response is to multiply my number by 10, floor it into an integer, then divide it by 10 again to turn it back into a float. It doesn’t work.
I keep ending up with results like 2.100002 or 8.699998
Numbers that end in .0 or .5 work properly but everything else is off by .000002 and I can’t figure out why.
Even the ‘Snap to grid’ node doesn’t work, it has the exact same result as the problem above only it can be off by up to .000005
This should be so simple and there are sooooo many people out there trying to do this same type of thing so why doesn’t Unreal still not have a node for this!?
That’s not quite what I was doing, but that’s interesting it’s getting it correct - doing a similar thing in c++ still gives the float variance - I’m not sure I’d trust it in all applications…
The reason is that floating point numbers aren’t decimal.
It’s literally impossible to represent 0.1 exactly in a floating point number. Computer can’t do it.
0.5, 0.25, 0.125, 0.0625, and other numbers that are even fractions of 2 are exactly representable.
The problem is that you’re doing this:
Try to represent a value that’s exactly 0.1
Present the value that’s stored above exactly
What you should be doing is:
Represent whatever the number actually is
Present the number with rounding in presentation, for example using ToText (float)
…pretty straight forward. You want a tenth decimal place, you multiply by ten, truncate, then divide by ten. You want a hundredth decimal place, you use 100 and so forth.
EDIT:
Seems like you have to cache the value in a variable though. For some reason I can’t use it directly.
These ways all work, but I have a way that I personally like just because it keeps things relatively simple to look at by using Modulo.
NOTE: This will not give you exactly the same mathematical result of other methods shown above. This technically doesn’t round the value, but instead just removes any remainder below a certain decimal. Whether or not this is okay depends on why you’re rounding it. I like this method if I’m just trying to make a float more human-readable, where precision is less important.
For example, if you were doing it to one decimal point, both values 1.92 and 1.99 would return 1.9, instead of 1 and 2.