Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalize a System.Decimal - strip trailing zeros

Tags:

c#

format

decimal

I've got a pretty compact way of removing trailing zeros in decimal values but I'd prefer a way that doesn't involve string roundtripping as mine currently does. This is my current solution:

var value = 0.010m;
value = decimal.Parse(value.ToString("G29"));
Console.WriteLine(value); // prints 0.01 (not 0.010)

So it works, but do you have an even better way?

Also, as a secondary question is decimalValue.ToString() 100% conformant to xs:decimal?

like image 477
Bent Rasmussen Avatar asked Oct 10 '22 04:10

Bent Rasmussen


1 Answers

It doesn't really matter how many SF the number is stored as but rather what happens when you output it.

Try

// The number of #'s is the number of decimal places you want to display
Console.WriteLine(value.ToString("0.###############");
// Prints 0.01
like image 177
John Oxley Avatar answered Oct 18 '22 12:10

John Oxley