【问题标题】:Texbox to decimal with culture info带有文化信息的十进制文本框
【发布时间】:2016-04-24 11:04:03
【问题描述】:

我的 texbox 值转换为小数时遇到问题。 在比利时,十进制字符是“,”。它在 UI 上运行良好,但是一旦我将这些值传递给我的方法,它就不再读取“,”。

我尝试过使用文化信息,但没有运气。

在这里,它仍然以逗号作为分隔符为我提供了正确的值。所以例如这里它仍然是“85,00”的正确值

   if (rdoNew.Checked)
        {
            productPresenter.addProduct(
                                    txtProductCode.Text, txtProductName.Text, txtProductDescription.Text,
                                    Convert.ToDecimal(txtPriceExVat.Text, CultureInfo.InvariantCulture), Convert.ToDecimal(txtPriceIncVat.Text, CultureInfo.InvariantCulture), 
                                    txtProductSerial.Text, Convert.ToBoolean(checkboxIsService.Checked)
                                    );
        }
        else
        {
            productPresenter.updateProduct(Convert.ToInt32(cbProducts.SelectedValue), txtProductCode.Text, txtProductName.Text, txtProductDescription.Text,
                                    Convert.ToDecimal(txtPriceExVat.Text, CultureInfo.InvariantCulture), Convert.ToDecimal(txtPriceIncVat.Text, CultureInfo.InvariantCulture),
                                    txtProductSerial.Text, Convert.ToBoolean(checkboxIsService.Checked));
        }

但是这里的价格 priceExVat 和 priceIncVat,例如现在是“8500”

 public void addProduct(string productCode, string productName, string productDescription, decimal priceExVat, decimal priceIncVat, string serialNumber, bool isService)
     {
         tbl_products product = new tbl_products();
         product.ProductCode = productCode;
         product.ProductName = productName;
         product.ProductDescription = productDescription;
         product.ProductPriceExVat = priceExVat;
         product.ProductPriceInclVat = priceIncVat;
         product.ProductSerialNumber = serialNumber;
         product.IsService = isService;

我是如何理解的,当我使用 CultureInfo.InvariantCulture 时,字符串会转换为正确的文化信息。但我认为我在这里错了。

【问题讨论】:

    标签: c# decimal cultureinfo


    【解决方案1】:

    因为您从不在您的代码中使用您当前的文化或特定文化(可以是 fr-BEnl-BE,因为您没有指定它)。

    由于InvariantCulture 使用, 作为NumberGroupSeparator,您的代码认为此分隔符是千位分隔符而不是十进制分隔符。

    这就是为什么您的结果将是 8500 而不是 85,00(我假设您将 85000 写为错字)

    如果您在代码中使用那种特定文化,我认为应该没问题。

    decimal.Parse("85,00", CultureInfo.GetCultureInfo("fr-BE"));
    // 85,00
    decimal.Parse("85,00", CultureInfo.GetCultureInfo("nl-BE"));
    // 85,00
    

    【讨论】:

    • 谢谢!我实际上不知道不变文化使用“,”作为数字组分隔符。我已经在某个地方读过它,它可以像这样使用,它会从机器中获取信息。但显然不是。那么坏信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2010-09-19
    相关资源
    最近更新 更多