【问题标题】:Format user inputed currency格式化用户输入货币
【发布时间】:2013-09-07 17:06:06
【问题描述】:

这是我的问题,我正在尝试将 {"C:O"} 格式化为 console.readline,但我收到了方法名称预期错误。这是我现在拥有的:

money = double.Parse(Console.ReadLine()(string.Format("{O:C}")));

【问题讨论】:

  • 用户以何种格式向控制台输入数据? {C:0} 是字符串数据类型的格式,对双精度/十进制没有意义。
  • @sll 请注意,他们正在尝试调用Console.ReadLine() 的返回值。除非那是一个错字。

标签: c# .net windows console console.readline


【解决方案1】:

除了语法错误,你一般应该用decimal来表示钱,因为double上的很多操作都会导致舍入错误。

我会推荐这样的东西:

string input = Console.ReadLine();
decimal money = decimal.Parse(input);

或者在一行中:

decimal money = decimal.Parse(Console.ReadLine());

Parse 将在输入无效输入时抛出异常(例如"foo")。您可能希望使用TryParse 更安全一点:

decimal money;
if (!decimal.TryParse(Console.ReadLine(), out money))
{
    Console.WriteLine("Invalid input");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多