Simon_Weaver
Simon_Weaver

Reputation: 145890

Format decimal with fewest possible digits after decimal separator

I am storing a variety of different sizes as a decimal in SQL server, such as:

10oz, 3.3oz, 100ml, 1.75litres

When I pull this number out as a decimal and do ToString() I end up with too many extra digits such as

10.000, 3.300, 100.00, 1.750

What I want is basically this :

decimal.Parse("1.7500").ToString().TrimEnd('0', '.')

to get me 1.75 or 10

I cannot seem to figure out the format string for this.

In Visual Studio debugger if I do decimal.Parse("1.7500") it will show it to me as 1.75 but when I do ToString() it becomes 1.7500.

Decimal.Round(...) is no good because the format is not fixed.

Upvotes: 2

Views: 313

Answers (2)

vcsjones
vcsjones

Reputation: 141588

This looks a bit odd but it does work:

var dec = 1.0004000m;
var str = dec.ToString("0;#############################.#############################");

It seems best in this case to take advantage of custom formatters.

You can always write an extension method out of the ToString so that you don't have to type all the #'s that often. 'Course if you need digit grouping, insert the appropriate grouping separator where needed.

Upvotes: 1

Malcolm O'Hare
Malcolm O'Hare

Reputation: 4999

Regex.Replace(decimal.Parse("1.7500").ToString(),"^(0+)|(?<=\.\d+)(0+)$")

Upvotes: 0

Related Questions