- Home /
Changing float lenght
Hello,
I have float variables like 4.101814. How can I reduce its lenght to 2, so it would look like this: 4.10
Thanks!
Comment
Best Answer
Answer by sharat · Aug 22, 2011 at 04:02 PM
float val = 4.101814f;
float roundedVal = 0.01f * Mathf.Round(100.0f * val);
For efficiency you should use 100.0f but besides that absolutely right.
Oh for all Unityscript users that example is written in C# but the actual computation is the same:
// UnityScript
var val = 4.101814;
var roundedVal = 0.01 * $$anonymous$$athf.Round(100.0 * val);
Answer by Bunny83 · Aug 22, 2011 at 04:39 PM
If you want to display the float as string you should use a custom format string.
In your case
// C#
float val = 4.101814f;
Debuf.Log("The value is "+val.ToString("0.00"));
// prints: "The value is 4.10"
// UnityScript
var val = 4.101814f;
Debuf.Log("The value is "+val.ToString("0.00"));
// prints: "The value is 4.10"
Your answer
![](https://koobas.hobune.stream/wayback/20220612190021im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rounding Off A Float? 2 Answers
Check increasing float variable 1 Answer
HOW TO ADD AND REMOVE VARIABLES ALREADY DECLARED IN A LIST 1 Answer
How do I add something on to a float. 1 Answer
Float to Int 4 Answers