代码之家  ›  专栏  ›  技术社区  ›  Al Lelopath

字符串到十进制,始终有两个小数位

  •  0
  • Al Lelopath  · 技术社区  · 6 年前

    我有一个要转换成十进制的字符串。输入字符串时不能有小数位,例如“123”或2个小数位,例如“123.45”,或者有点尴尬,1个小数位“123.3”。我要显示号码(属性 invoice.Amount 哪种类型 decimal )两位小数。下面的代码就是这样做的。不过,我觉得可以写得更好。怎么用?

    decimal newDecimal;
    bool isDecimal = Decimal.TryParse(InvoiceDialog.InvoiceAmount, out newDecimal);
    string twoDecimalPlaces = newDecimal.ToString("########.00");
    invoice.Amount = Convert.ToDecimal(twoDecimalPlaces);
    

    在某种程度上,我不明白,对于字符串格式“.00”,0做什么和做什么。如果是“.”会有什么不同?

    4 回复  |  直到 6 年前
        1
  •  2
  •   Dmitrii Bychenko    6 年前

    # 是一个 可选择的 数字时间 0 是一个 强制性的 数字

    例如

     decimal d = 12.3M;
    
     // d with exactly 2 digits after decimal point
     Console.WriteLine(d.ToString("########.00"));
     // d with at most 2 digits after decimal point 
     Console.WriteLine(d.ToString("########.##"));
    

    结果:

    12.30   // exactly 2 digits after decimal point: fractional part padded by 0
    12.3    // at most 2 digits after decimal point: one digit - 3 - is enough
    
        2
  •  1
  •   Adrian    6 年前

    基本上,表示可选,其中0是必需的。 至于更好的解释,如果你把然后,如果数字是可用于fullfil占位符,它将被添加,如果不是,它将被忽略。

    但是,输入0是不同的,因为它总是为您输入一个值。

    你可以把两者结合起来。

    String.Format("{0:0.##}", 222.222222); //222.22美元

    String.Format("{0:0.##}", 222.2); //222.2个

    String.Format("{0:0.0#}", 222.2) //222.2个

        3
  •  1
  •   kjr1995    6 年前

    “”是可选的,而“0”将显示数字或0。

    例如,

    var x = 5.67;
    x.ToString("##.###"); // 5.67
    x.ToString("00.000"); // 05.670
    x.ToString("##.##0"); // 5.670
    

    如果你只关心你有多少个小数位,我建议你用

    x.ToString("f2"); // 5.67
    

    得到两个小数点。

    更多信息请访问 http://www.independent-software.com/net-string-formatting-in-csharp-cheat-sheet.html/ .

        4
  •  1
  •   user1672994    6 年前

    你不需要转换 decimal string 对两个小数位进行格式化。你可以使用 decimal.Round 方法直接。你可以看看 here .

    所以你的代码可以转换成

        decimal newDecimal;
        Decimal.TryParse(s, out newDecimal);
    
        newDecimal = decimal.Round(newDecimal, 2, MidpointRounding.AwayFromZero);
    

    上述代码也可以用c 7.0声明表达式简化为

        Decimal.TryParse(s, out decimal newDecimal);
    
        newDecimal = decimal.Round(newDecimal, 2, MidpointRounding.AwayFromZero);
    

    现在newdecimal将有一个2精度的值。

    你可以查一下 this 活小提琴。