简体   繁体   English

C#:如何将十进制转换为字符串而不转换为指数表示

[英]C#: How to convert decimal to string without converting to exponential representation

For instance, I have an object array with some values. 例如,我有一个带有一些值的对象数组。 It can be decimal, double ,int or strings. 它可以是十进制,双精度,int或字符串。 object[] oo = {0.000278121, 0.000078125m, "Hello",1}; For instance when converting this values to string, the second value becomes 7.8125E-05. 例如,当将此值转换为字符串时,第二个值变为7.8125E-05。 But first value stays as in array. 但是第一个值保持不变。 So how to differentiate parsing logic for that types, and parse all decimal values in the same format? 那么,如何区分该类型的解析逻辑,并以相同格式解析所有十进制值? Full code: 完整代码:

object[] oo = {0.000278121, 0.000078125,"Hello",1};
string[] ss = oo.Select(x => x.ToString()).ToArray();
Console.WriteLine(string.Join("|",ss)); // 0.000278121|7.8125E-05

Firstly, that's not a decimal , it's a double . 首先,这不是decimal ,而是double Use 0.000278121m, 0.000078125m if you want decimal s. 如果要decimal s 0.000278121m, 0.000078125m请使用0.000278121m, 0.000078125m

To force a full length string representation without exponentials use .ToString("0.#################") for double. 要强制使用不带指数的全长字符串表示形式,请使用.ToString("0.#################")作为double。 With decimal the default does this so .ToString() as you have would work fine. 使用十进制默认情况下.ToString()因此.ToString()可以正常工作。

Instead of below line: 而不是下面的行:

string[] ss = oo.Select(x => x.ToString()).ToArray();

You can use below line your code: 您可以在下面的代码行中使用:

I am assuming that 10 is maximum number of decimal digits you can have in the input sets. 我假设10是输入集中可以包含的最大十进制数字。 If there are more then change N10 to some other number. 如果还有更多,则将N10更改为其他数字。

string[] ss = oo.Select(x => ((double)x).ToString("N10")).ToArray();

If you have a disparate collection of objects, treat each type differently: 如果您有不同的对象集合,请分别对待每种类型:

var outStrings = new List<string>();
object[] oo = { 0.000278121, 0.000078125, "Hello World" };
foreach (var ooItem in oo) {
    if (ooItem is double dOo) {
        outStrings.Add(dOo.ToString("0.#################"));
    } else {
        outStrings.Add(ooItem.ToString());
    }
}

If you have many types that you want to treat individually, use a pattern matching switch statement 如果您要单独处理许多类型,请使用模式匹配switch语句

I believe you could use double.ToString(string) method. 我相信您可以使用double.ToString(string)方法。 See: https://docs.microsoft.com/en-us/dotnet/api/system.double.tostring?view=netframework-4.7.2#System_Double_ToString_System_String_ 请参阅: https : //docs.microsoft.com/zh-cn/dotnet/api/system.double.tostring?view=netframework-4.7.2#System_Double_ToString_System_String_

The parameter can be either custom numeric format strings ( https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings ) or standard numeric format strings ( https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings?view=netframework-4.7.2#NFormatString ). 该参数可以是自定义数字格式字符串( https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/custom-numeric-format-strings )或标准数字格式字符串( https:// docs.microsoft.com/zh-CN/dotnet/standard/base-types/standard-numeric-format-strings?view=netframework-4.7.2#NFormatString )。

The precision specifier of "N" format specifier should be between 0 and 99 (N0 ~ N99), otherwise the ToString method will return the string passed as parameter instead. “ N”格式说明符的精度说明符应介于0到99(N0〜N99)之间,否则ToString方法将返回作为参数传递的字符串。 You could do double.ToString("N99") , which will return the string in numeric form in its highest precision. 您可以执行double.ToString("N99") ,它将以最高的精度以数字形式返回字符串。 The problem with this is that if you do 0.000078125.ToString("N99") , the output would have lots of trailing 0s, like: 0.0000781250000000000... . 这样做的问题是,如果执行0.000078125.ToString("N99") ,则输出将有很多尾随0,例如: 0.0000781250000000000...

To overcome this, you could use string.TrimEnd(char) method. 为了克服这个问题,您可以使用string.TrimEnd(char)方法。 0.000078125.ToString("N99").TrimEnd('0') will trim the trailing zeros, so the output can be 0.000078125. 0.000078125.ToString(“ N99”)。TrimEnd('0')将修剪尾随的零,因此输出可以为0.000078125。

In the given example code, this can be applied as: 在给定的示例代码中,可以将其应用为:

//Avoid boxing - specify types whenever possible, or use generic
double[] oo = {0.000278121, 0.000078125};
string[] ss = oo.Select(x => x.ToString("N99").TrimEnd('0')).ToArray();
Console.WriteLine(string.Join("|",ss)); // 0.000278121|0.000078125

Edit: I should have read the question more carefully, changing the type of oo would not be suitable in your case. 编辑:我应该更仔细地阅读问题,更改oo的类型不适合您的情况。 However, the general idea is the same; 但是,总体思路是相同的。 Cast the object to double, Use ToString(string) method with appropriate precision, then trim the trailing zeros. 将对象强制转换为double,以适当的精度使用ToString(string)方法,然后修剪尾随的零。

You can check that the type of object is double by doing obj is double , and furthermore, cast it back to double by obj is double dbl (Pattern matching). 您可以通过使obj is double来检查对象的类型是否obj is double ,并且通过obj is double dbl (模式匹配)将其转换回double。

Edit 2: 编辑2:

public static IEnumerable<string> AllToString(IEnumerable<object> objArray)
{
    foreach (object obj in objArray)
    {
        switch (obj)
        {
            case double dbl:
                yield return dbl.ToString("N99").TrimEnd('0');
                break;
            case bool b:
                yield return b.ToString();
                break;
            case int i:
                yield return i.ToString();
                break;
            case short s:
                yield return s.ToString();
                break;
            case string str:
                yield return str;
                break;
            case float flt:
                yield return flt.ToString("N99").TrimEnd('0');
                break;
            case decimal dcm:
                yield return dcm.ToString("N99").TrimEnd('0');
                break;
            case byte bt:
                yield return bt.ToString();
                break;
            case char ch:
                yield return ch.ToString();
                break;
            case uint ui:
                yield return ui.ToString();
                break;
            case ushort us:
                yield return us.ToString();
                break;
            case sbyte sb:
                yield return sb.ToString();
                break;
            case long ln:
                yield return ln.ToString();
                break;
            case ulong uln:
                yield return uln.ToString();
                break;
            case null:
                yield return null; //new string()?
                break;
            case DateTime dt:
                yield return dt.ToString();
                break;
            case TimeSpan ts:
                yield return ts.ToString();
                break;
            default: //Fallback
                yield return obj.ToString();
                break;
        }
    }
}

Pass the object array to the method, then call .ToArray() or .ToList() if required. 将对象数组传递给方法,然后根据需要调用.ToArray()或.ToList()。 This will convert every item in the array/list of object to a collection of strings. 这会将对象数组/列表中的每个项目转换为字符串集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM