Converting Decimal to string with non-default format

前端 未结 4 1192
醉酒成梦
醉酒成梦 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: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);
    

提交回复
热议问题