- Home /
Show 1 decimal only when printing a float
Is there any way to print a float and have it only show 1 decimal?
e.g Float = 2.123131231, I want it to print Float = 2.1
At the moment im using Mathf.Floor(float) but that shows only the int.
Thanks in advance!
Answer by aldonaletto · Nov 06, 2011 at 11:38 PM
You can use ToString("F1"):
var division: float = 1.0/3;
guiText.text = division.ToString("F1");
"F1" shows one decimal digit, "F2" shows 2 digits, and so on.
Answer by vatara · Nov 06, 2011 at 11:33 PM
Javascript:
var number = Mathf.PI;
Debug.Log(Mathf.Round(number * 10)/10);
C#:
float number = Mathf.PI;
Debug.Log(number.ToString("0.0"));
The Javascript version can use ToString in the same way as C#. This code works as-is in both C# and JS:
var number = $$anonymous$$athf.PI;
Debug.Log(number.ToString("0.0"));
Strange that we have to use this method and that number.toFixed(1); doesn't work.
Thanks to everyone who answered this!
It's not strange at all, since there is no .toFixed method in .NET/$$anonymous$$ono. Unity does not use Javascript, even though Unityscript may be called that sometimes.
Your answer
Follow this Question
Related Questions
Mathf.Lerp not working as expected 2 Answers
Mathf.Lerp float between 0 and 1 based on boolean input 3 Answers
Comparing float value to zero 1 Answer
Periodic fraction gets converted to int 1 Answer
float precision, again 0 Answers