How does the rounding of the string format work?

Asked

Viewed 345 times

5

Consider the following code snippet:

decimal myValue = 3.045M;

Console.WriteLine("Result by Math.Round = " + Math.Round(myValue, 2));
Console.WriteLine("Result by string.Format = " + string.Format(CultureInfo.GetCultureInfo("pt-BR"), "{0:C}", myValue));

The results are:

// Result by Math.Round = 3.04
// Result by string.Format = R$3,05

I know the Math.Round() uses IEEE 754, section 4, in accordance with that documentation, also called standard Banker’s rounding.

But why the string.Format() as the specified crop returns a different result? I realized that the result is the same for different crops, as if the rounding method were different from the Math.Round().

This document from the IBGE agrees with the IEEE standard.

What is the reason for the difference and what method would be the most appropriate for financial systems?

2 answers

5


The simple answer is that they are different, there is no commitment to being equal because they serve different purposes, so it is always good to use what you really want. There’s no dichotomy between them.

If you want to do it right, round it up and present the already rounded result. I always remember that texts are not numbers even though people insist on thinking they are, if you want to work with numbers work with them and leave the textual representation only to present the exact number you already have without running the risk of inconsistencies.

Numbers exist by themselves on the computer and they are the ones that can be manipulated with calculations, what we see on a screen or other form of presentation are texts that represent these numbers. So the data you already have is a number and do everything with it until you need to present, including possible rounding.

Something tells me you don’t think one happens String.Format() in the first case, but all Writexxx() and other methods that present information take objects that are not texts and apply a String.Format() before submitting, because these methods only know how to present texts (strings), and not numbers). The same goes for some ToString(), which is used in this case, after all it is not possible to concatenate a number with a text, so there is an implicit conversion to text when calling the concatenation and this is done with the same function.

I managed to find a answer that gives some support on this since he is one of the people who worked on the project and he argues that it is because of compatibility with a mistake made a long time ago.

-1

In my opinion you could use Console.WriteLine("Result is = " + Format(myValue, "#.##0,0#")); This way you would keep it original value, without making changes and keep the real value.

As a financial system, I believe that losing a few tenths can make a difference at the end of the calculations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.