2

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.

Community
  • 1
  • 1
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • If you're targetting .NET 4.0, the answer in this thread might help: http://stackoverflow.com/questions/4298719/parse-decimal-and-filter-extra-0-on-the-right – keyboardP Dec 24 '11 at 03:53
  • thanks @keyboardP - tried searching but just couldn't find the existing answers. this one is good too : http://stackoverflow.com/questions/3104615/best-way-to-display-decimal-without-trailing-zeros-in-c-sharp – Simon_Weaver Dec 24 '11 at 04:10
  • If you cast to `float` and display with `G` format, it will remove the trailing `0`. – John Alexiou Dec 24 '11 at 04:20
  • I'd be very interested to see what Visual Studio is doing to display a decimal rounded as 1.75. (and @ja72 I switched to a decimal because a float was giving me some nasty 0.00000012 type rounding errors) – Simon_Weaver Dec 24 '11 at 04:27
  • @ja72 That will lose precision. – vcsjones Dec 24 '11 at 04:43

2 Answers2

1

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.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
0
Regex.Replace(decimal.Parse("1.7500").ToString(),"^(0+)|(?<=\.\d+)(0+)$")
Malcolm O'Hare
  • 4,879
  • 3
  • 33
  • 53