【问题标题】:How to put decimal point in a whole number如何将小数点放在整数中
【发布时间】:2019-10-21 10:44:47
【问题描述】:

我正在从银行读取一个带有一串数字的文本文件。 0000000010050,这个字符串的金额是$100.50,但是有没有办法在字符串中插入小数点呢?这是我的代码。

string amount = 0000000010050; 
string f_amount = "";
string ff_amount = "";
decimal d_amount = 0;

f_amount = amount.Trim();
d_amount = int.Parse(f_amount.TrimStart('0')); // this part removes the zeros and the output is 10050.
ff_amount = string.Format("{0:0,0.00}", d_amount); // this line outputs 10050.00

如何使输出看起来像这样100.50

【问题讨论】:

  • 但是有没有办法在字符串中插入小数点?是的,string.Insert
  • 将金额解析为十进制(而不是int),除以100然后格式化。
  • @Selvin 我如何设置它将小数点放在最后 2 位之前?
  • @Selvin LOL 我忘了,我的大脑已经筋疲力尽了啧啧啧。谢谢。我会试试这个。

标签: c# text-formatting asp.net-core-mvc-2.0


【解决方案1】:

先把字符串转成十进制,这样应用string.Format

string.Format("{0:#.00}", Convert.ToDecimal(bankString) / 100);

这将给出结果 100.50

https://dotnetfiddle.net/WrRVFo

【讨论】:

  • 一般来说,这是比较好的处理方式(转换成十进制,然后更正小数点的位置)。但是,我会改用decimal.TryParse,以防万一有无法转换的坏数据:decimal.TryParse(original, out var d) ? (d / 100).ToString("0.00") : null
【解决方案2】:

类似这样的事情(让我们考虑CultureInfo

  using System.Globalization;

  ... 

  string amount = "0000000010050";

  amount = amount
    .Insert(amount.Length - CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalDigits,
            CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator)
    .TrimStart('0');

【讨论】:

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