首页 > 解决方案 > 转换为双精度不允许小数点后为零

问题描述

我在 WPF 和 C# 中工作,遇到了一个我认为源于我的转换器的问题。我有一个文本框,在页面加载时,一个 INT 被转换为一个 DOUBLE 并显示出来。例子:

在我输入 24.0 后会发生什么,它立即恢复为 24。我可以通过输入 24.9 然后在需要的位置输入 0 来实现 24.09。我试图弄乱我的转换器,认为这是我何时/如何将其转换为双精度的问题,但它仍然产生相同的结果。

这是转换器的代码:

    //This takes in an int and converts it to a double with two decimal places
    [ValueConversion(typeof(object), typeof(double))]
    public class conDouble : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double db = System.Convert.ToDouble(value);
            return (db / 100.00).ToString();
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ToInt32((System.Convert.ToDouble(value) * 100));
        }
    }

正则表达式有问题的文本框:

<Page.Resources>
        <system:String x:Key="regexDouble">^\d+(\.\d{1,2})?$</system:String>            
</Page.Resources>
<TextBox Name="txtItemPrice" Grid.Column="12" Grid.ColumnSpan="2" Grid.Row="4" HorizontalAlignment="Stretch" VerticalAlignment="Center" IsEnabled="False" 
                 Validation.ErrorTemplate="{StaticResource validationTemplate}"
                 Style="{StaticResource textStyleTextBox}">
            <TextBox.Text>
                <Binding Path="intPrice" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" Converter="{StaticResource Double}">
                    <Binding.ValidationRules>
                        <classobjects:RegexValidation Expression="{StaticResource regexDouble}"/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

最后是我的验证器:

public class RegexValidation : ValidationRule
    {
        private string pattern;
        private Regex regex;
        public string Expression
        {
            get { return pattern; }
            set
            {
                pattern = value;
                regex = new Regex(pattern, RegexOptions.IgnoreCase);
            }
        }
        public RegexValidation() { }
        public override ValidationResult Validate(object value, CultureInfo ultureInfo)
        {
            if (value == null || !regex.IsMatch(value.ToString()))
            {
                return new ValidationResult(false, "Illegal Characters");
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }

    }

标签: c#wpfconverter

解决方案


return (db / 100.00).ToString();正如 John Wu 所说,在您的转换器中,该行将双精度转换为字符串。作为测试,如果您运行表达式(24.0).ToString(),则结果为“24”。由于您正在对价格进行建模,因此您可以执行类似的操作(db / 100.00).ToString("F2"),这将导致“24.00”,或者(db / 100.00).ToString("C"),这将导致 $24.00。您可以在https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings找到完整的格式字符串列表。我没有完全遵循您的实施,但这将防止 24.0 自动恢复为 24 的情况。

另外,请注意,对于金融数据来说,十进制是比双精度更好的数据类型。有关更多信息,请参阅此链接:十进制与双精度!- 我应该使用哪一个以及何时使用?


推荐阅读