日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#中關于double.ToString()的用法_C#教程

作者:kingkee ? 更新時間: 2023-06-18 編程語言

C# double.ToString()的用法

C# 中 double 類型的數據,有時需要格式化顯示為字符串(保留N位有效數字或者是保留N位小數),可以使用 double.ToString("參數") 方法。

下面列出幾個常用的方法

(F)Fixed point:string str1=temp.ToString("f1"); ? ? ? ? ? ? ?//保留一位小數 四舍五入 結果:3.1

(F)Fixed point:string str2=temp.ToString("f2"); ? ? ? ? ? ? ?//保留兩位小數,四舍五入 下面一次類推 結果:3.14

(N)Number:string str2=temp.ToString("N"); ? ? ? ? ? ? ? ? ? //保留 結果:3.14

(G)General (default):string str2=temp.ToString("G"); ? ?//保留 結果:3.1415926

(P)Percent:string str2=temp.ToString("P"); ? ? ? ? ? ? ? ? ? //保留 結果:314.16%

(E)Scientific:string str2=temp.ToString("E"); ? ? ? ? ? ? ? ? //保留 結果E:3.141593E+000

(C)Currency:string str2=temp.ToString("C"); ? ? ? ? ? ? ? ?//保留 結果:¥3.14

C# Double 按有效數字 ToString

將double轉換為n有效數字的字符

我找了各種帖子包括在微軟文檔搜索 ‘significant digits’;最接近的是ToString(“Gx”)

但是返回是不大于這個x有效位的字符串, 舉例

double a=1.2;
string s=a.ToString("G3");

得到1.2而不是1.20

所以就寫了一個函數

? ? ? ? string DoubleToStringSignificantDigits(double a, int SignificantDigits)
? ? ? ? {
? ? ? ? ? ? string formaterG = 'G' + SignificantDigits.ToString("N0");
? ? ? ? ? ? string strResult = a.ToString(formaterG);
? ? ? ? ? ? int resultLength = SignificantDigits;
? ? ? ? ? ? if (strResult.IndexOf('-') >= 0) resultLength++;
? ? ? ? ? ? if (strResult.IndexOf('.') >= 0) resultLength++;
? ? ? ? ? ? if (Math.Abs(a) < 1) resultLength++; //絕對值小于1,有一個整數0不算有效位
? ? ? ? ? ? if (strResult.Length < resultLength)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if (strResult.IndexOf('.') < 0)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? strResult += '.';
? ? ? ? ? ? ? ? ? ? resultLength++;
?? ??? ?}
? ? ? ? ? ? ? ? strResult = strResult.PadRight(resultLength, '0');
? ? ? ? ? ? }
? ? ? ? ? ? return (strResult);
? ? ? ? ?}

結果

double[] x = new double[] { 100, 99, 12.12, 1.1234, 1.2, 0.2, 0.12345 , -0.2, -1.2, -123};
轉換
DoubleToStringSignificantDigits(x[i], 3)
得到
100
99.0
12.1
1.12
0.200
0.123
-0.200
-1.20
-123

總結

原文鏈接:https://blog.csdn.net/kingkee/article/details/100926729

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新