Home > other >  Double is not rounded using Math.Round function?
Double is not rounded using Math.Round function?

Time:12-14

I'm creating new model and one of the model's properties is BruttoPrice (nullable-double type) and to that property i want to assign my Item3 (nullable-double type) value but rounded to 2 decimal places - so i"m using Math.Round function but it's not working

Assigning item3 to bruttoPrice

.

var model = new Model
            {
                BruttoPrice = Math.Round(val.Item3 ?? 0, 2),
            };

My model output

.

CodePudding user response:

The problem is that you're expecting a double to be able to store an exact value to a given number of decimal digits.

The precise double value closest to 153.4 is 153.400000000000005684341886080801486968994140625 - which is being displayed as 153.40000000000001.

There's nothing more that Math.Round can do there - there's no double value closer to 153.4.

If this is just for formatting purposes, you should format to 2 decimal places rather than rounding the data.

If the actual value matters, and you want precise decimal values, you should use decimal instead of double.

  • Related