C#浮點數保留位數


C#浮點數保留位數

這里用String.Forma("{0:F}",x);來解決。

下面是試驗和截圖


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM