Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
hi double d = 123.45;
math.round(d,0).tostring();
but it print 124
i want to print only 123 not 124
plz help.
Posted
Comments
ZurdoDev 3-Sep-14 11:31am    
When I run that code it prints 123.
Sergey Alexandrovich Kryukov 3-Sep-14 12:07pm    
Of course. :-)
—SA

You are badly mistaken: rounding really gives you 123, not 124. Your observation was wrong.

More importantly: you should understand that you should not do rounding directly in this and most other cases. This has some danger of using rounded value as some intermediate result and loosing precision. Instead, prefer using rounding embedded in formatting operation:
C#
string myOnScreenValue = string.Format("{0:###}", d); // 3 positions
string myOtherOnScreenValue = string.Format("{0:F0}", d); // better: 0 digits in fractional part

Please see:
http://msdn.microsoft.com/en-us/library/kfsatb94%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx[^].

—SA
 
Share this answer
 
v2
Comments
CPallini 3-Sep-14 12:34pm    
5.
Sergey Alexandrovich Kryukov 3-Sep-14 13:23pm    
Thank you, Carlo.
—SA
You can use Math.Truncate()

C#
double d = 123.45;
var output = Math.Truncate(d).ToString();


More at: http://msdn.microsoft.com/en-us/library/c2eabd70(v=vs.110).aspx[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 3-Sep-14 12:09pm    
No! Another wrong answer! Can you pay at least some attention?
1) Round does provide correct answer; why would you trust OP on that?! 2) Round is not needed.
When rounded is needed, truncate is totally wrong.
—SA

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