C#浮點數保留位數
下面是試驗和截圖
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tst
{
class Program
{
static void Main(string[] args)
{
double b = 123456.123456789;
Console.WriteLine(String.Format("{0:F}", b));//保留2位小數(默認)
Console.WriteLine(String.Format("{0:F1}", b));//保留1位小數
Console.WriteLine(String.Format("{0:F2}", b));//保留2位小數
Console.WriteLine(String.Format("{0:F3}", b));//保留3位小數
Console.WriteLine(String.Format("{0:F4}", b));//保留4位小數
Console.WriteLine(String.Format("{0:F5}", b));//保留5位小數
Console.WriteLine(String.Format("{0:F6}", b));//保留6位小數
Console.WriteLine(String.Format("{0:F7}", b));//保留7位小數
Console.WriteLine(String.Format("{0:F8}", b));//保留8位小數
Console.WriteLine(String.Format("{0:F9}", b));//保留9位小數
Console.WriteLine(String.Format("{0:F10}", b));//保留10位小數
/*保留指定位小數*/
int n = 5;
Console.WriteLine("保留指定的位數:n = {0}",n);
Console.WriteLine(String.Format("{0:F" + String.Format("{0}",n)+"}", b));//
Console.ReadKey();
}
}
}
