C#数字转字符串保留2位小数

时间:2021-04-26 13:58:04   收藏:0   阅读:0
double a = 123456, b = 123456.1, c = 123456.12, d = 123456.123, e = 123456.126;
Console.WriteLine(a.ToString("N")); //123,456.00
Console.WriteLine(b.ToString("N")); //123,456.10
Console.WriteLine(c.ToString("N")); //123,456.12
Console.WriteLine(d.ToString("N")); //123,456.12
Console.WriteLine(e.ToString("N")); //123,456.13
Console.WriteLine();

Console.WriteLine(a.ToString("N2")); //123,456.00
Console.WriteLine(b.ToString("N2")); //123,456.10
Console.WriteLine(c.ToString("N2")); //123,456.12
Console.WriteLine(d.ToString("N2")); //123,456.12
Console.WriteLine(e.ToString("N2")); //123,456.13
Console.WriteLine();

Console.WriteLine(a.ToString("F2")); //123456.00
Console.WriteLine(b.ToString("F2")); //123456.10
Console.WriteLine(c.ToString("F2")); //123456.12
Console.WriteLine(d.ToString("F2")); //123456.12
Console.WriteLine(e.ToString("F2")); //123456.13
Console.WriteLine();

Console.WriteLine(a.ToString("0.00")); //123456.00
Console.WriteLine(b.ToString("0.00")); //123456.10
Console.WriteLine(c.ToString("0.00")); //123456.12
Console.WriteLine(d.ToString("0.00")); //123456.12
Console.WriteLine(e.ToString("0.00")); //123456.13
Console.WriteLine();

Console.WriteLine(a.ToString("G")); //123456
Console.WriteLine(b.ToString("G")); //123456.1
Console.WriteLine(c.ToString("G")); //123456.12
Console.WriteLine(d.ToString("G")); //123456.123
Console.WriteLine(e.ToString("G")); //123456.126
Console.WriteLine();

//本地货币
Console.WriteLine(a.ToString("C")); //NT$123,456
Console.WriteLine(b.ToString("C")); //NT$123,456.1
Console.WriteLine(c.ToString("C")); //NT$123,456.12
Console.WriteLine(d.ToString("C")); //NT$123,456.123
Console.WriteLine(e.ToString("C")); //NT$123,456.126
Console.WriteLine();
Console.Read();

 

原创:c# 数字转字符串保留两位小数 - HotSky - 博客园 (cnblogs.com)

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!