NumberBox not showing actual value in WinUI 3

Issue

A number box in my WinUI 3 application is displaying the float value 5.94 as "5.9399999995". This number box is bound to a float property of a view model. There are other number boxes that are bound to different instances of the same view model, and the others display their float values fine (fine meaning showing 2 decimal digits, defined by the number formatter bound to all these number boxes).

The number box Xaml definition:

<NumberBox
  Value="{x:Bind Path=MainVM.ViewModel[5].SomeNumber, Mode=TwoWay}"
  />

As said before, each of these number boxes has a number formatter attached that limits the decimal digits to 2 digits, but that still doesn’t explain why 5.94 is being displayed not as 5.94.

Solution

Binary floating point math is like this.

But in this case, you can implement a custom number formatter, for example like this:

public class DoubleFormatter : INumberFormatter2, INumberParser
{
    public virtual string Format { get; set; } = "{0:F2}"; // by default we use this but you can change it in the XAML declaration
    public virtual string FormatDouble(double value) => string.Format(Format, value);
    public virtual double? ParseDouble(string text) => double.TryParse(text, out var dbl) ? dbl : null;

    // we only support doubles
    public string FormatInt(long value) => throw new NotSupportedException();
    public string FormatUInt(ulong value) => throw new NotSupportedException();
    public long? ParseInt(string text) => throw new NotSupportedException();
    public ulong? ParseUInt(string text) => throw new NotSupportedException();
}

Note: it’s not documented AFAIK but an INumberFormatter2 must also implement INumberParser otherwise you get "invalid argument" of more exotic cryptic errors…

Sample XAML:

<StackPanel>
    <StackPanel.Resources>
        <local:DoubleFormatter x:Key="df" /> <!-- change Format here -->
    </StackPanel.Resources>
    <NumberBox NumberFormatter="{StaticResource df}" Value="{x:Bind MyFloatValue, Mode=TwoWay}" />
</StackPanel>

Answered By – Simon Mourier

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published