-1

I have the following database values

 0.0012
 0.00197
 0.002  
 0.00011
 0.065000  
 0.002001
 0.9624
 1
 1.23
 1.232
 1.5
 1.0924

I know I need to multiply the figures by a 1000 to get the correct answers which is what I do then try to format for the correct number format. I've tried different string formats for example below code:

txtTop_Measure.Text = String.Format("{0:f2}", (System.Convert.ToDecimal(_dataRowMeasureData["Top_Measure"]) * 1000));

which gives me the output below. Some are correct and some are not.

 1.20
 1.97
 2.00  
 0.11
 0.07
 2.00
 962.40
 1000.00
 1230.00
 1232.00
 1.500.00
 1092.40

The output I require is below, but I can't figure out which string format to use to get the output below.

 1.20
 1.97
 2  
 0.11
 0.0650
 2.0010
 962.40
 1000
 1230
 1232
 1.500
 1092.40

I need the brain power of the community to resolve this please. Thanks

Ruth Amui
  • 143
  • 1
  • 2
  • 12
  • http://stackoverflow.com/questions/9707611/format-decimal-2-places-no-trailing-zeroes?rq=1 - there's answers here on how to strip the trailing zeroes – Charleh Oct 06 '16 at 12:06
  • 6
    I'm not clear on how you determine which format to use for which number. It looks like if it doesn't have a fraction, then you don't want anything after the decimal, but then it's not clear at all how many trailing zeros you want if there is a fraction. At first I though you wanted an even number of numbers after the decimal, but `1.500` wouldn't fit with that. – juharr Oct 06 '16 at 12:07
  • Yeah good point @juharr on some of the outputs you have 2 decimal places but only 1 significant digit past the decimal point, yet on others you have no trailing decimals... – Charleh Oct 06 '16 at 12:08
  • @juharr looking at the source of 1.5, I think `1.500` should be `1500` and it was a typo of the OP trying to do `1,500`. Look at the "bad" version `1.500.00`. It also is the only 4 digit number with a `,` so I think it was a typo. – Scott Chamberlain Oct 06 '16 at 16:03
  • Related: http://stackoverflow.com/a/16091580/380384 – John Alexiou Oct 06 '16 at 17:43
  • Possible duplicate of [Round a double to x significant figures](http://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures) – John Alexiou Oct 06 '16 at 17:44

1 Answers1

-1

This is an example how to format the string depending on its decimal places. First I run a modulo-n-check. Depending on that result I choose the format.

        var s = "0.0012";
        var x = Convert.ToDecimal(s)*1000%1000 == 0
            ? String.Format("{0}", Convert.ToInt64(s) * 1000)
            : String.Format("{0:f2}", Convert.ToDecimal(s) * 1000);
codelab
  • 406
  • 3
  • 14