Click here to Skip to main content
15,908,841 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to round of answer

C#
decimal a = decimal.Parse(Label20.Text);
        decimal b = decimal.Parse(Label15.Text);
        decimal c = b - a;

        Label22.Text = c.ToString();
Posted
Comments
Sergey Alexandrovich Kryukov 10-Jul-15 2:30am    
Why? I'm not joking. In all questions about rounding, no one really needed rounding, they needed rounded string representation of the number. Most likely, you too. Mathematical rounding not only superfluous, it can be an extra danger, accidentally leading to critical loss of precision.
—SA
[no name] 20-Jul-15 12:08pm    
"Nobody" needs rounding, really?
I have a BOM, where e.g. each component is in %:
The Display is e.g.
# CONC ID
1 0.0000 Mat1

Not rounded (at the right time/place) it is unsure wheter CONC is now really 0 or maybe 0.0000001, which may come to effect as soon the amount for Mat1 Needs to be calculated for production....if 0 no Mat1, otherwhise Mat1 is needed.
Sergey Alexandrovich Kryukov 20-Jul-15 12:11pm    
No nobody, but it's almost never needed. I don't mean sophisticated things like random number generators.

Probably, you miss the point: I mean directly use rounding. You need rounding, but usually, indirect, through formatting. As soon as you say "display", this is not rounding per se, this is getting formatted sting of rounded value. You never get intermediate rounded result of a numeric type, and this is good.

You will understand it if you read my answer and referenced articles properly.

—SA
[no name] 20-Jul-15 12:21pm    
as you say "display":
But that is the point. The user sees "0.000" but the real value is maybe "0.00001". So for me rounding is very important, but a very dangerous and sometimes difficult thing to do it at the right time/place.
Sergey Alexandrovich Kryukov 20-Jul-15 12:30pm    
I already explained that. Use proper formatting. Rounding won't help you.
—SA

C#
Math.Round(Convert.ToDecimal(Label20.Text)), 2);


OR

C#
double doubleNumber;
doubleNumber= 17843.1234;
doubleNumber.ToString("F2",CultureInfo.InvariantCulture));
// Displays 17843.12
 
Share this answer
 
Please see my comment to the question. I don't see where you need rounding. Rather, you need proper string formatting, to get rounded value. Please see:
https://msdn.microsoft.com/en-us/library/fzeeb5cd%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/0c899ak8%28v=vs.110%29.aspx[^].

—SA
 
Share this answer
 
v3
Comments
Sanket Saxena 20-Jul-15 8:13am    
my +5 for the solution SA
Sergey Alexandrovich Kryukov 20-Jul-15 8:52am    
Thank you, Sanket.
—SA
Read the documentation : Decimal.Round Method (Decimal)[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900