c# - 转换为双精度不允许小数点后为零
问题描述
我在 WPF 和 C# 中工作,遇到了一个我认为源于我的转换器的问题。我有一个文本框,在页面加载时,一个 INT 被转换为一个 DOUBLE 并显示出来。例子:
- 初始值:32.99
- 可以改为:
- 24
- 24.99
- 24.9
- 无法更改为:
- 24.09
在我输入 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);
}
}
}
解决方案
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 的情况。
另外,请注意,对于金融数据来说,十进制是比双精度更好的数据类型。有关更多信息,请参阅此链接:十进制与双精度!- 我应该使用哪一个以及何时使用?
推荐阅读
- python - 传递多组参数
- javascript - 无法将此绑定到功能
- android - 服务 UUID 上的 BluetoothLeScanner ScanFilter 不起作用
- google-cloud-firestore - Firestore 不等于 (!=) 计为范围过滤器
- apache-nifi - 尝试使用 NifI 添加基于条件的字段
- git - GIT - 从提交的分支中保存分支和主文件,其中与主文件不同
- javascript - 环境变量:使用custom-enviroment-variables.json,定义应用程序机密的正确方法是什么
- php - Symfony 5通过ajax返回表单错误
- asp.net-core - 强制 ASP .NET Core 2.1 使用 HTTPS 并返回 400 错误
- php - 如何从另一个 PHP 文件中的类调用函数以进行路由?