[C#][小技巧] double 轉字串問題,我不要 +E

2012-11-06

 

這需求有點詭異,但是依然就是發生了,

一個double 數值

double doubleValue = 900000000 * 9000000000 + 9000000000;
把他轉成 string 會長怎樣呢?!

答案是  8.100000009E+18


這不是我預期的答案,就人類世界來看我希望看到的數字是 8100000009000000000


這時候要動點小手腳( 嘆氣~~






public string ToFloatingPointString(double value)
{
var rxScientific = new Regex(@"^(?<sign>-?)(?<head>\d+)(\.(?<tail>\d*?)0*)?E(?<exponent>[+\-]\d+)$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
string result = value.ToString("r", NumberFormatInfo.InvariantInfo);
var match = rxScientific.Match(result);
if (match.Success)
{
int exponent = int.Parse(match.Groups["exponent"].Value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo);
var builder = new StringBuilder(result.Length + Math.Abs(exponent));
builder.Append(match.Groups["sign"].Value);
if (exponent >= 0)
{
builder.Append(match.Groups["head"].Value);
string tail = match.Groups["tail"].Value;
if (exponent < tail.Length)
{
builder.Append(tail, 0, exponent);
builder.Append(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
builder.Append(tail, exponent, tail.Length - exponent);
}
else
{
builder.Append(tail);
builder.Append('0', exponent - tail.Length);
}
}
else
{
builder.Append('0');
builder.Append(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
builder.Append('0', (-exponent) - 1);
builder.Append(match.Groups["head"].Value);
builder.Append(match.Groups["tail"].Value);
}
result = builder.ToString();
}
return result;
}




這時候叫用測試一下




 
double doubleValue = 900000000 * 9000000000 + 9000000000;
Response.Write(doubleValue+"<br />");
Response.Write(ToFloatingPointString(doubleValue));


答案 :



2012-09-05_225545



給有遇到同樣詭異需求的人 :[


後記:



其實,後來發現只要




Response.Write(doubleValue.ToString("#") + "<br />");



就可以解決了 = =


參考來源:



http://stackoverflow.com/questions/1546113/double-to-string-conversion-without-scientific-notation


當麻許的超技八 2014 | Donma Hsu Design.