Converting Decimal to string with non-default format

前端 未结 4 1155
醉酒成梦
醉酒成梦 2021-01-07 20:36

I need to convert decimal to string, in this rulers:

120.00 - \"120\"
120.01 - \"120.01\"
120.50 - \"120.50\"
相关标签:
4条回答
  • 2021-01-07 21:18

    Use, decimal.ToString() method. You can specify format with that method if you need:

    decimal d = 120.00;
    string ds = d.ToString("#,#.00#");
    // ds is a formated string of d's value
    
    0 讨论(0)
  • 2021-01-07 21:19

    You can use the decimal.ToString override to specify a formatting.

    decimal amount = 120.00m;
    string str = amount.ToString("0.00");
    

    This can also be used when using String.Format.

    Console.WriteLine("{0:0.00}", amount); 
    

    In the case of your first rule, it cannot be done on one line.

    decimal amount = 120.00m;
    string str = amount.ToString("0.00").Replace(".00", String.Empty);
    
    0 讨论(0)
  • 2021-01-07 21:19

    There are different overloads for decimal.ToString based on what formatting you want.

    Example

    decimal d = 5.00
    Console.WriteLine(d.ToString("C")); // for currency
    

    See below for other overloads... specifier is what you put into the ToString(specifier)

    MSDN Documentation on Decimal.ToString

    decimal value = 16325.62m; string specifier;

    // Use standard numeric format specifiers.
    specifier = "G";
    Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
    // Displays:    G: 16325.62
    specifier = "C";
    Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
    // Displays:    C: $16,325.62
    specifier = "E04";
    Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
    // Displays:    E04: 1.6326E+004
    specifier = "F";
    Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
    // Displays:    F: 16325.62
    specifier = "N";
    Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
    // Displays:    N: 16,325.62
    specifier = "P";
    Console.WriteLine("{0}: {1}", specifier, (value/10000).ToString(specifier));
    // Displays:    P: 163.26 %
    
    // Use custom numeric format specifiers.
    specifier = "0,0.000";
    Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
    // Displays:    0,0.000: 16,325.620
    specifier = "#,#.00#;(#,#.00#)";
    Console.WriteLine("{0}: {1}", specifier, (value*-1).ToString(specifier));
    // Displays:    #,#.00#;(#,#.00#): (16,325.62)
    
    0 讨论(0)
  • 2021-01-07 21:23

    You can use decimal.Tostring() method

    pls go through this link for more info

    0 讨论(0)
提交回复
热议问题