简体   繁体   中英

C# Dynamic Decimal Formatting

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM