簡體   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