-
August 30th, 2011, 05:00 PM
#1
Junior Member
rounding float values in C#
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()
-
August 31st, 2011, 03:46 PM
#2
Simple, basic idea (pseudo-code as I don't know C#):
Code:
var a = 5.827671;
var b,c;
b = int( ( a + .005 ) * 100 );
c = b / 100;
return c;
The addition of 0.005 is to make sure it's rounded up or down correctly.
Last edited by SirDice; August 31st, 2011 at 03:48 PM.
Oliver's Law:
Experience is something you don't get until just after you need it.
-
August 31st, 2011, 08:11 PM
#3
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:
Code:
decimal d = 5.827671;
you could use
Code:
string rounded = d.ToString("0.##")
I believe in making the world safe for our children, but not our children’s children, because I don’t think children should be having sex. -- Jack Handey
-
September 1st, 2011, 04:02 AM
#4
Isn't there some sort of String.format? I feel like that would be cleaner than changing it to a string just to round.
-
September 1st, 2011, 01:56 PM
#5
Originally Posted by metguru
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.
I believe in making the world safe for our children, but not our children’s children, because I don’t think children should be having sex. -- Jack Handey
Similar Threads
-
By warriorfan808 in forum General Programming Questions
Replies: 4
Last Post: November 28th, 2005, 09:50 PM
-
By ch4r in forum Other Tutorials Forum
Replies: 0
Last Post: May 30th, 2005, 09:29 PM
-
By Kamikaze Badger in forum Code Review
Replies: 4
Last Post: March 30th, 2005, 01:55 PM
-
By Neg in forum AntiOnline's General Chit Chat
Replies: 1
Last Post: August 2nd, 2004, 07:57 PM
-
By jinxy in forum Operating Systems
Replies: 3
Last Post: May 5th, 2004, 06:57 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|