Share via


How to set the number of decimal places.

Question

Wednesday, February 18, 2015 1:20 AM

Just wondering what and where the code would be to set the number of decimal places when calculating an answer.

All replies (2)

Wednesday, February 18, 2015 8:09 AM ✅Answered

you can use Math.Round method

double result = Math.Round(calculatedValue, noOfDecimal);

if you are assigning the value directly to some control, like textbox in c# code then you can directly use it

resultTextBox.Text = Math.Round(calcResult, 6); // for 6 decimals

if you are binding the value from viewmodel then set in the view model

....

ResultValue = Math.Round(calcResult, 6);

...

<TextBox Text="{Binding ResultValue}" />


Wednesday, February 18, 2015 9:18 AM ✅Answered | 2 votes

Depending on exactly what result you want you could alternatively format the result to a set number of decimal places.

This is not so good for financial applications where they want the total of 10 transactions to match the total of each number displayed but can be kind of important for scientific ones.

eg

someNumber.ToString("N3"));

Gives you three decimal places without changing the someNumber.

If this turned out to be wpf then you have stringformat you can use on a binding.

Hope that helps.
Recent Technet articles: Property List Editing ;   Dynamic XAML