I have a float data type in C#.
Let's say its value is
5.827671
and I want to concat/round it to the nearest 100th place
5.83
How would I do that?
The value is ported to a string by
floatvalue.ToString()
Printable View
I have a float data type in C#.
Let's say its value is
5.827671
and I want to concat/round it to the nearest 100th place
5.83
How would I do that?
The value is ported to a string by
floatvalue.ToString()
Simple, basic idea (pseudo-code as I don't know C#):
The addition of 0.005 is to make sure it's rounded up or down correctly.Code:var a = 5.827671;
var b,c;
b = int( ( a + .005 ) * 100 );
c = b / 100;
return c;
If you don't intend on calculating further, you can also use ToString() formatting to get it rounded.
So say you have your code like such:
you could useCode:decimal d = 5.827671;
Code:string rounded = d.ToString("0.##")
Isn't there some sort of String.format? I feel like that would be cleaner than changing it to a string just to round.
There is a String.Format but from what i can tell, it does the same thing as yourStringVar.ToString("YourFormatHere").
And after looking a little bit, there is Math.Round(d,i) where you pass your decimal or double and the number of decimal places and it will pass back either a decimal or a double. That seems to be the best option if you plan to continue calculating.