Search code examples
formatblazortextfieldmudblazor

Format bound double property in MudBlazor textfield


I have a model with double values which is bound to MudTextfield in this way:

<MudTextField @bind-Value="product.Price" Label="Price"/>

@code {
  Product product = new Product { Name="Test-Abo", Price=199.12345 }
}

MudTextfield converts double to string and when string is edited it converts back to double, so that is working fine. But I have two problems:

  1. In my culture, the decimal point is written as a comma so the textfield shows a comma but I want to have a decimal dot like in C#.
  2. I want the text field to truncate the decimals to two even if the value in the model has more

How can I do it?


Solution

  • On a MudTextField there are a few options to convert the value of type T (in your case double) to string:

    You can either use:
    Culture ... to override the default UI Culture
    Format ... to override the ToString() format
    These will actually configure the default converter

    Or:
    Converter ... to override the default converter with a custom converter with your own conversion funcs between T and string and vice-versa.

    To solve your problem, set the Culture to Invariant which will always use the dot (.) as a decimal separator and set the Format to "F2" which will truncate your floating point value to two decimals:

    <MudTextField @bind-Value="product.Price" Label="Price" Format="F2" 
                  Culture="@CultureInfo.InvariantCulture"/>