【问题标题】:How to check whether a given string is Decimal or not in C#?如何在 C# 中检查给定字符串是否为十进制?
【发布时间】:2012-10-26 04:44:41
【问题描述】:

我已经用65.34, 65,45, 34.45这样的字符串值完成了这个

一切都返回 True ...

public void test()
{
   string value = "65" 0r "65.0" 0r "1,234.54";
   decimal number;

   if (Decimal.TryParse(value, out number))
      MessageBox.Show(value);
   else
      MessageBox.Show("Unable to parse '{0}'.", value);
 }

这一切都返回一个十进制..

         If I type "0.65" .. I need to show error and it i type "65" it has to be exectued.

【问题讨论】:

  • "如果我输入 65 .. 我需要显示它的整数...如果我输入 65.0 那么我必须显示错误" ​​但是,您的问题是关于解析小数...我使困惑。 6565.0 是有效的十进制值。
  • 先生,如果我输入 .65,我必须显示错误。如果我输入 24.23 我不必显示错误.. 我该怎么做
  • 您尚未提出可回答的问题。有人要求你澄清你的问题——这可能会消除反对票。 (编辑你的问题并澄清,不要把它放在 cmets 中。)
  • 看起来您想从浮点数中获取小数位数,或者至少验证它不是整数。看起来像:stackoverflow.com/questions/1040707/…
  • 你想让 .65 无效吗?因为它低于 1 还是因为它不是以 0 开头?否则,我会接受 .65 作为有效的小数。

标签: c# decimal tryparse


【解决方案1】:

你有两个选择

1.使用Regex

2.使用以下方法求小数位数

 static decimal CountDigitsAfterDecimalPoint(decimal decimalNumber)
        {
            int[] bits = Decimal.GetBits(decimalNumber);
            int exponent = bits[3] >> 16;
            int result = exponent;
            long lowDecimal = bits[0] | (bits[1] >> 8);
            while ((lowDecimal % 10) == 0)
            {
                result--;
                lowDecimal /= 10;
            }

            return result;
        }

【讨论】:

    猜你喜欢
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多