My DataGrid receives double variables, I want to truncate them to two or three decimal places. My xaml code:
<DataGrid Name="McDataGrid" ItemsSource="{Binding}" Visibility="Collapsed" HorizontalAlignment="Center"
Margin="0, 200, 0, 0" VerticalAlignment="Top" CanUserAddRows="False" />
All of my C# code that touches the datagrid:
McDataGrid.DataContext = fillingDataGridUsingDataTable(string input).DefaultView;
McDataGrid.Visibility = Visibility.Visible;
fillingDataGridUsingDataTable(input) is a function that returns a DataTable with headers in string and values in double.
CodePudding user response:
You can use the ToString
together with the format specifier F
with a precision specifier (Standard format specifiers). The DataGrid
will convert the double value to a string
anyway, so ToString
will do it. Use the overload that accepts a IFormatProvider
to make the result use the correct decimal separator for the current system's language.
The following example creates numeric string
from a double
value with a precision of 3 decimal places:
double value = 1.23456;
var numericString = value.ToString("F3", CultureInfo.CurrentCulture); // "1.235"
To convert the double
value use the Math.Round
helper:
double value = 1.23456;
double roundValue = Math.Round(value, 3); // 1.235