float val = num1/num2;
The result of val is 2.7456
I need result as 2.75
How can i get it
float val = num1/num2;
The result of val is 2.7456
I need result as 2.75
How can i get it
You can use Math class of C# to do this-
System.Math.Round(val,2);// Edited
This is a right way!!
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.
Try using this if you would like to round to 2 decimal places:
val.ToString(“F2”);
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.
float val = num1/num2;
val = (float)System.Math.Round(val, 2);