- Home /
round float with 2 decimal
float val = num1/num2;
The result of val is 2.7456
I need result as 2.75
How can i get it
Answer by DeveshPandey · Sep 12, 2013 at 12:22 PM
You can use Math class of C# to do this-
System.Math.Round(val,2);// Edited
This is a right way!!
mathf.roundtoint is that you need : http://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$athf.RoundToInt.html
I don't want want int value. Please read my question.
Seriously. If you don't understand the basics of typing and casting, you will not be able to finish a game project. End of. This is fundamental stuff, and it will hit you later on, and hard. Learn the basics - I'm not just saying that because I don't want to help you, the opposite. I'm saying it because unless you know the basics, you will fail.
Answer by Hoeloe · Sep 12, 2013 at 12:18 PM
Expanding on the other answer, you should use that method, which is Math.Round(val, 2);
. The val
here refers to the value you're rounding, while the 2 refers to the number of decimal places to round to.
Old answer for archive purposes
You can do quite a simple trick actually: Multiply it by 100, round it, divide it by 100. So, you multiply it by 100, giving 274.56. Then you round it, giving 275. Then divide it by 100 again, giving 2.75.
Alternatively, you can use C#s string.Format
, like so: string.Format("0.0", val)
, which will display only 2 decimal places as a string value. You can then parse the string back into a float.
Of these two methods, I recommend the first one.
Yeah, there's no rounding there. Try what I suggested, or use the method suggested by DeveshPandey, using System.$$anonymous$$ath.Round(val,2);
(Thanks for that, DeveshPandy, wasn't aware of those overloaded versions of $$anonymous$$ath.Round)
Answer by whoopdeedoo03 · Aug 08, 2017 at 08:46 AM
Try using this if you would like to round to 2 decimal places:
val.ToString("F2");
Answer by EdgeKing810 · Aug 03, 2018 at 10:29 AM
Hey... I've got an idea.
Why don't you try assigning the following to a variable.
val2 = val.ToString("F2"); //This will convert your value to 2 decimal points.
Then, you could do the following to get it back as a float.
val3 = float.Parse(val2);
I'm writing this for future Unity users who may come across this. Oh and sorry if I've misspelled something in the code.
Answer by dahal2871 · Oct 27, 2020 at 11:14 AM
float val = num1/num2;
val = (float)System.Math.Round(val, 2);
Your answer
![](https://koobas.hobune.stream/wayback/20220613114019im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
A node in a childnode? 1 Answer
C# round transform.position floats to .5 2 Answers
Shown decimal places 2 Answers
2D rigidbody makes my character slowly rise 1 Answer
Is it possible to round down 0.99 to 0? 2 Answers