Double ToString - No Scientific Notation [duplicate]

こ雲淡風輕ζ 提交于 2019-11-26 11:29:03

问题


This question already has an answer here:

  • Double to string conversion without scientific notation 17 answers

I just came across the wonderful \"feature\" that .NET will by default do Double.ToString() using scientific notation if there are enough decimal places.

.005.ToString() // \".005\"
.00005.ToString() // \"5E-05\" 

Does anyone know an efficient way to get this to appear as a string in standard (non-scientific) notation?

I\'ve seen this question, but the top two answers seem kind of hacky to me as they both do Double.ToString() and then just reformat the results.

Thanks for any help.

EDIT:

The desired output:

.00005.ToString() == \".00005\"

EDIT2:

What is with all the duplicate and close votes? I specifically say in the question that the similar question does not have a satisfactory answer. People on this website get way too power happy.

MY SOLUTION:

In case it\'s useful to anyone:

/// <summary>
/// Converts the double to a standard notation string.
/// </summary>
/// <param name=\"d\">The double to convert.</param>
/// <returns>The double as a standard notation string.</returns>
public static String ToStandardNotationString(this double d)
{
    //Keeps precision of double up to is maximum
    return d.ToString(\".#####################################################################################################################################################################################################################################################################################################################################\");

}

NOTE: This only works for values > 1. I haven\'t found an efficient way to do this for all values yet.


回答1:


See the Standard and Custom Numeric Format Strings. I think you're looking for ".################":

.00005.ToString(".################") // returns ".00005"

It's somewhat hackish, yes, but it works, as long as you don't have more than that many places after the decimal. If you do, you might want to use a StringBuilder to build out about 330 #s in your string (double.Epsilon is on the order of E-324).



来源:https://stackoverflow.com/questions/14964737/double-tostring-no-scientific-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!