Need to round float to one decimal point. Why is it so difficult?

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!?

1 Like

Like this?

LogBlueprintUserMessages: [BP_CENTCOM_ANX_C_0] 0.914151
0.91
LogBlueprintUserMessages: [BP_CENTCOM_ANX_C_0] 0.912442
0.91
LogBlueprintUserMessages: [BP_CENTCOM_ANX_C_0] 0.651357
0.65
LogBlueprintUserMessages: [BP_CENTCOM_ANX_C_0] 0.764183
0.76
LogBlueprintUserMessages: [BP_CENTCOM_ANX_C_0] 0.691763
0.69
LogBlueprintUserMessages: [BP_CENTCOM_ANX_C_0] 0.072817
0.07
LogBlueprintUserMessages: [BP_CENTCOM_ANX_C_0] 0.859615
0.86

I used the following node which is part of the free Low Entry Extended Library (marketplace):

The “to Text” converter node has similar. I imagine you could look at the c++ to see what they do, and copy it to your own function, if you wanted.

Hi Lowenfas,

If you’re just wanting it as 1 decimal place for displaying you can do it like this:

I see. Tested an it’s doing exactly what you said. Seems that some floats will never be exactly right.

If you scale everything up by 10, your grid can be an integer then.

If you just use an integer instead, everything will be out by the exact same amount.

But yeah most of the time, .000005 is negligible.

1 Like

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…

1 Like

Yeah it’s the conversion to float that makes it inaccurate. Float by it’s very definition, is inaccurate.

1 Like

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:

  1. Try to represent a value that’s exactly 0.1
  2. Present the value that’s stored above exactly

What you should be doing is:

  1. Represent whatever the number actually is
  2. Present the number with rounding in presentation, for example using ToText (float)

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

1 Like