How to round a float to two decimals?

I want to round a float, but I want it to always have 2 numbers after the dot. even if its say 10.00, so it doesn’t mess the string. problem is that if I multiply by 100, integer and then divide by 100, if the number is .0 it doesn’t show the zeroes, and also after a while, the precision gets off and I start getting results like 10.0000446554 or so.

how do I do so?

I believe this has already been answered here: How can I set float precision? - Programming & Scripting - Unreal Engine Forums

What you are doing is multiplying your number by the 10^number of point you want (in your case 2), using floor to cut off the tail and then dividing by that first number to get your formatted result

this answer doesn’t solve the fact that I want to force an integer to have 2 zero decimals. but there’s an answer above the best answer on that post that solves it with the “ToText (float)” node.

That doesn’t even work. It should and I can’t understand what the problem is but it still gives answers like 12.499998 and 30.100002

If you convert a number to a float, you will get float variance. Float by it’s very definition is inaccurate. It’s like taking a digital sound wave and turning into analogue sound and then measuring a specific point and getting errors compared to the digital values. It’s like an analogue version of a number. You can’t convert to a float without getting some variance sometimes.

This was just answered here, too:

Use ToText (float) to present a floating point number with a fixed number of decimal digits.

Yeah the problem is, if you NEED a float, that doesn’t help. Converting it back to a float to be able to use it, brings back the variance.

You never need the float to be at exactly 0.1.
If you need that, you should use integers, at 10x the resolution.
What you need when it comes to floats, is to present it as if it’s at 0.1.

Fixed point is not a bad thing, and it’s not uncommon in things like combat system mechanics. Define anything in units of 1/1000, store it in an int, divide and round when presenting.

Btw, if you DO use floats, and you round when presenting, note that 0.99 will round to 1.0, but if you have some game mechanic that kicks in when you hit 1.0, the user will be confused why that mechanic doesn’t kick in.

Some programmers say that “you can’t trust floats” or “floats aren’t precise,” which isn’t actually true. However floats behave in a very special, well-defined way, which is not the way that one might naively expect if one is used only to decimals, and fixed-point numbers (like you’d write them on graph paper or whatever.)

2 Likes