Download

[Solved] How to round floats? (0.234378996=0.23)

Hi guys!
I need to round floats (0.234378996=0.23, 12.3349=12.33, etc.)

I’m trying to use “Snap to grid (0.01)”.
Sometimes it returns expected results (0.23), but sometimes it returns ugly long numbers (0.234378996)

How to properly round floats?
(I know this is simple question, but I’ve searched it on forums, didn’t find the answer)

float.JPG


10 chars…

Hi guys! Thx for the answer, but it DOESN’T work at all! It still is returning ugly long floats
Why is that??

That above does work. Your problem lies somewhere else. This does the rounding only once, so if your float changes via calculations you need to round it again every time.

If this is for display purposes, you can set Maximum Fractional Digits like so:

https://docs.unrealengine.com/en-US/…oat/index.html

Screenshot your Blueprints and the output of Print String.

Hi! Here’s my simple blueprint:
https://blueprintue.com/blueprint/0x6wo_3s/
Can you guys tell me what is wrong? Thanks!

Output (ugly long floats):
PIE: Play in editor total start time 0,132 seconds.
LogBlueprintUserMessages: [BP_Test] 57.129997
LogBlueprintUserMessages: [BP_Test] 36.809998
LogBlueprintUserMessages: [BP_Test] 33.200001
LogBlueprintUserMessages: [BP_Test] 25.09
LogBlueprintUserMessages: [BP_Test] 67.07
LogBlueprintUserMessages: [BP_Test] 91.650002
LogBlueprintUserMessages: [BP_Test] 23.519999
LogBlueprintUserMessages: [BP_Test] 89.970001
LogBlueprintUserMessages: [BP_Test] 84.189995
LogBlueprintUserMessages: [BP_Test] 62.82
LogBlueprintUserMessages: [BP_Test] 71.769997
LogBlueprintUserMessages: [BP_Test] 59.969997
LogBlueprintUserMessages: [BP_Test] 78.769997
LogBlueprintUserMessages: [BP_Test] 48.289997
LogBlueprintUserMessages: [BP_Test] 45.950001
LogBlueprintUserMessages: [BP_Test] 70.93
LogBlueprintUserMessages: [BP_Test] 64.830002
LogBlueprintUserMessages: [BP_Test] 80.32

That solution should work, but it doesn’t. Quite weird…
You can try like this, but you will have a string output:

or you can use “to text (float)”, expand it by clicking on the down arrow, and set the maximum fractional digits to 2, but you will have a text value.

Rounding a float is not that simple. Floats are by design not 100% accurate so if you want a 100% accurate number you will need to use integers. Floats are used because they can display very large numbers without requiring a lot of memory and overhead.

So you have two options either format the float using “Float To Text” as mentioned above or convert the float to an Integer.

Got it! Thanks a lot, guys!
Currently I guess “Float To Text” will be good enough for me.

For anyone else coming here late to the game… the Float to Text to Float if you need it is:
float x = FCString::Atof(*FString::SanitizeFloat(FMath::FRandRange( min, max )).Left(precision + 2));

replace “FMath::FRandRange( min, max )” with your float.

1 Like