简体   繁体   English

限制双精度字符的最大字符数

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

Is there an elegant way to convert a double to a string so it's rounded to fit within a maximum total length but is otherwise similar to the default neutral culture format? 是否有一种优雅的方法可以将双精度型转换为字符串,以便将其四舍五入以适合最大总长度,但又类似于默认的中性文化格式?

I don't want to just limit the number of decimal places because the number of characters used for sign and exponent might change, or it might not be in scientific notation. 我不想仅限制小数位数,因为用于符号和指数的字符数可能会更改,或者可能不是科学计数法。

Eg, with a maximum of 20 characters 例如,最多20个字符

-1.23456789012345E-67

should appear as 应该显示为

-1.2345678901235E-67

while

123 should appear as 123 , not 1.23E+02 . 123应该显示为123 ,而不是1.23E+02

As Sintar mentioned G format specifier should do all you need. 正如Sintar所提到的,G格式说明符应做所有您需要的事情。

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

The following is a extension method might be helpful: 以下是扩展方法可能会有所帮助:

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