Float precission in C++

Hey there!

I need to “clamp” a given random number in order to have just 1 decimal number.

Example:

After using FMath::RandRange(), random number is: 1.4563246. The clamped number I want is 1.4 or rount it to 1.5. I tried FMat::Clamp but is not working properly or maybe I don’t know how to use it.

Anybody could help me? Thank you so much in advance.

Regards,

j0s3m4.

FMath::Clamp() clamps the number to an interval (make it “stay inside the interval”). So:

FMath::Clamp(1.4563246, 1.4, 1.5) == 1.4563246
FMath::Clamp(2.0, 1.4, 1.5) == 1.5
FMath::Clamp(0.0, 1.4, 1.5) == 1.4  

What you want is rounding:

FMath::RoundHalfToZero(10.0 * 1.4563246) / 10.0 == 1.5
FMath::RoundHalfToZero(10.0 * 1.4463246) / 10.0 == 1.4

Cheers

2 Likes

If what you need is “true” decimal calculations and your project is windows based, I have a FDecimal C++ plugin for UE4 here:

If you want this for diplaying purposes and not actual caluclation use this. Otherwise Muelas answer is a good approach.

Thank you so much everybody for your help. I didn’t realize that basic math would help me hahaha. You were right, Muelas.Aitzol.

Again, thank you.

Regards,
j0s3m4

You were right too, pulp_user, but the previous answer fits better with my logic.

Thank you so much!