Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I had few decimal variable and i want to forced all the value for that variable will always show me with 2 decimal places.
However, i fail to get value with 2 decimal places with Math.Round().

Example for my variable value:
C#
decimal value1 = 123.899m;
decimal value2 = 123;

decimal amount1 = Math.Round(value1, 2);
decimal amount2 = Math.Round(value2, 2);

While the result i get is as below:
amount1 = 123.9
amount2 = 123

How could i get the result like "123.90" and "123.00 "without change it to string format?
Posted
Comments
PIEBALDconsult 24-Nov-15 22:07pm    
As Dave said; that's done at the presentation layer.

You don't do that. The presentation of two decimal places is only done on display to the user, not in your variables. Doing so introduces accuracy errors into your data over time.
 
Share this answer
 
Comments
Maciej Los 25-Nov-15 2:18am    
5ed!
Quote:
However, i fail to get value with 2 decimal places with Math.Round().
No it don't fail.
123.90 = 123.9 and 123.00 = 123
It is the right way to work with values with 2 decimal places.

To see the 2 decimals, it is a matter of formatting the values when you print them.
 
Share this answer
 
v2
Comments
Maciej Los 25-Nov-15 2:26am    
5ed!
Patrice T 25-Nov-15 3:19am    
Thank you
As Dave Kreskoviak[^] mentioned in solution 1 and ppolymorphe[^] in solution 2, your requirement is to display numeric value with 2 decimal places.

Please, see:
Standard Numeric Format Strings[^]
Custom Numeric Format Strings[^]

Now, you're able to display almost any format you want ;)
 
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