Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can i remove the one trailing zero for a decimal datatype, for example refer below sample data.
Input Values  >> Expected output values 
1)29.36       >> 29.36
2)29.00       >> 29.0
3)20.00       >> 20.0
4)29.50       >> 29.5
5)20          >> 20


What I have tried:

I tried to use float data type but if the input value is 29.00 it is showing as 29 only but i want it to be 29.0.
string formats also seems to be in accurate in this case as i need to remove second decimal value only if it zero.
Posted
Updated 17-Mar-18 8:16am
v3

Try a format string: "0.0#"
C#
decimal d;
d = 29.36M;
Console.WriteLine("{0}:{0:0.0#}", d);
d = 29.00M;
Console.WriteLine("{0}:{0:0.0#}", d);
d = 20.00M;
Console.WriteLine("{0}:{0:0.0#}", d);
d = 29.50M;
Console.WriteLine("{0}:{0:0.0#}", d);
Gives:
29.36:29.36
29.00:29.0
20.00:20.0
29.50:29.5
 
Share this answer
 
Comments
Maciej Los 17-Mar-18 9:36am    
5ed!
Ved_deV 17-Mar-18 14:18pm    
That is very good solution, thanks for your answer.
BUT, i missed one more point to mention in question which i updated now where i am expecting out put of 20 if the input s 20, and 29 if the input is 29,
Could you please help me in achieving this result too
In addition to solution #1 by OriginalGriff, i'd recommend to read this: Floating Point Demystified, Part 1[^] and this: What Every Computer Scientist Should Know About Floating-Point Arithmetic[^]

Conclusion: you want to display decimal value in custom format.

Standard Numeric Format Strings | Microsoft Docs[^]
Custom Numeric Format Strings | Microsoft Docs[^]
 
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