从文本框字符串转换为十进制

本文关键字:十进制 转换 字符串 文本 | 更新日期: 2023-09-27 18:36:31

我在将字符串转换为十进制时遇到问题。

decimal num = convert.todecimal(textbox1.text);

例如:如果文本框中的值为 2.50,则转换后我得到 num = 250。从字符串中删除 "."。我想获取写在文本框中的值。

请给出任何解决方案

从文本框字符串转换为十进制

这是Decimal.TryParse的小提琴:

https://dotnetfiddle.net/lDbfei

using System;
using System.Net;
public class Program
{
    public static void Main()
    {
        string myval = "put a number / your value here";
        decimal d = 0;
        var result = decimal.TryParse(myval, out d);
        Console.WriteLine(result);  
        Console.WriteLine(d);
    }
}
您可以使用静态

方法Decimal.TryParse

decimal myDec;
if (!Decimal.TryParse(mytextboxesContent, out myDec)) {
    // do whatever you want to if the content is not valid;
}

此方法的返回值还使您有机会对无效输入(例如"abc"或"1,3,4")做出反应。

试试这个:

decimal temp;
decimal.TryParse(textBox1.Text, out temp);

另一个例子:

 if(decimal.TryParse(textBox1.Text, out temp))
        {
            if(textBox1.Text.Contains(","))
            {
               textBox1.Text =  textBox1.Text.Replace(',', '.');
            }
        }

当您尝试转换来自用户的输入时,您不应盲目接受传递给您的所有内容,否则您将面临许多异常的风险。

这是TryParse系列方法的多版本背后的设计决策。检查您的输入是否可以转换为正确的数据类型,如果无法做到这一点,请使用返回值提供建议,不要引发异常。如果可以转换,则使用转换结果初始化传递的变量

然后,还有本地化问题。在某些区域性中,逗号表示数字小数部分的开始,而其他区域性则喜欢点符号。尝试使用CurrentCulture进行转换可以解决此问题,如果失败,请尝试InvariantCulture

string dec = "2.5"; // Not good for cultures that likes a comma as decimal symbol
decimal d;
if(!decimal.TryParse(dec, NumberStyles.AllowDecimalPoint, CultureInfo.CurrentCulture, out d))
{
    MessageBox.Show("Not a valid number in current culture");
    if(!decimal.TryParse(dec, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
        MessageBox.Show("Type a valid number please!");
}
MessageBox.Show("Valid number:" + d.ToString());

当然,如果您确定不可能为小数点分隔符输入无效符号,那么在 CultureInfo.InvariantCulture 本地化中只能使用一个 if。(但请注意一些简单的用户操作,例如从计算器复制/粘贴到文本框)。