簡體   English   中英

限制雙精度字符的最大字符數

[英]Limit the maximum number of characters in a double

是否有一種優雅的方法可以將雙精度型轉換為字符串,以便將其四舍五入以適合最大總長度,但又類似於默認的中性文化格式?

我不想僅限制小數位數,因為用於符號和指數的字符數可能會更改,或者可能不是科學計數法。

例如,最多20個字符

-1.23456789012345E-67

應該顯示為

-1.2345678901235E-67

123應該顯示為123 ,而不是1.23E+02

正如Sintar所提到的,G格式說明符應做所有您需要的事情。

double s = 1.31956544564371E+28;
Console.WriteLine("{0:G5}",s);  // will print 1.3196E+28

以下是擴展方法可能會有所幫助:

public static class doubleExtensions
{
    public static string GetDoubleString(this double source,int numOfChars){
        string  temp = "{0:G" + numOfChars + "}";
        return string.Format(temp,source);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM