繁体   English   中英

WPF 十进制自定义格式,无舍入

[英]WPF Decimal Custom Format without Rounding

MS文档说这是不可能的......希望我错过了文档中的一些内容。

想将十进制数格式化为:-9,999.000 使用StringFormat={}{0:#,0.000}有效,但这会“四舍五入”输入,因为我想“截断”输入。

为了测试,在WPF 表单中将此字符串格式应用于绑定到十进制属性的文本框

当我输入测试值时,实际的格式化值与预期的格式化值不匹配,因为格式字符串会自动“四舍五入”十进制值。

Enter     Expected     Actual
1111.999  1,111.999    1,111.999
1111.9999 1,111.999    1,112,000

MS 文档明确指出“0”占位符将始终四舍五入。 太好了,但我不想要那种行为。

问题:是否有不使用“0”的格式字符串来显示 3 个小数位(尾随零)? 还是有一个格式字符串在小数点后 3 位截断而不是在小数点后 3 位四舍五入?

我确实尝试StringFormat={}{0:#,0.###}但这会删除尾随零。 (还有StringFormat={}{F3} )。

Enter     Expected     Actual
1111.100  1,111.100    1,111.1

我能找到的最接近的解决方案是 [https://stackoverflow.com/questions/16914224/wpf-textbox-to-enter-decimal-values] 但没有一个答案真正涉及舍入与截断。

更新

xaml 代码,其中使用了 StringFormat。

 <TextBox Text="{Binding 
     TemplateNumber,
     StringFormat={}{0:F3},
     ValidatesOnDataErrors=True, 
     NotifyOnValidationError=True, 
     UpdateSourceTrigger=PropertyChanged, 
     Delay=500}"
     />

.Net 自定义数字格式一成不变,您无能为力。 具体来说:

“00”说明符使值四舍五入到小数点前最接近的数字,其中始终使用从零开始的四舍五入

如果你想应用不同类型的舍入,你可以使用Math.Round ,它接受一个参数来指定你想要的舍入类型(在你的情况下,它看起来像MidpointRounding.ToZeroMidpointRounding.ToNegativeInfinity ,很难告诉)。

您可以使用IValueConverter例如:

class DecimalConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {                        
            return string.Format("{0:F3}", value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (decimal.TryParse(value?.ToString().Replace(" ", ""), out decimal num1))
                return num1;
            return null;
        }
    }

将其添加到您的控件

<UserControl.Resources>
    <local:DecimalConverter x:Key="MyDecimalConverter"/>
</UserControl.Resources>

在文本框中使用

<TextBox Text={Binding ...., Converter={StaticResource MyDecimalConverter}}/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM