A weird thing happened when I tried to add 4 decimals (demanded in solution) to a 2-decimal double value:
Incorrect value:
var result = string.Format("{0:#,0.0000}", Math.Truncate(2.03*10000)/10000);
//Returns 2.0299
Correct values:
var result = string.Format("{0:#,0.0000}", Math.Truncate(2.02*10000)/10000);
//Returns 2.0200
And:
var result = string.Format("{0:#,0.0000}", Math.Truncate(2.04*10000)/10000);
//Returns 2.0400
Any idea why this happens ONLY to 2.03? 12.03 as input value returns 12.0300 btw.
I am lost. Please help.
There is no point multiplying by 10000 and dividing by 10000 here. You only risk introducing slight errors, like what you see here: note that doubles and floats use a base-2 representation and hence cannot exactly represent arbitrary decimal numbers.
This will give you what you want:
If you require perfect accuracy with decimal numbers, use the decimal type instead.