Search code examples
c#rounding

Round to 1 decimal place and should be double return type


if(cartWeight >= 10)
{
    totalPrice = 100;
    double price = totalPrice - (totalPrice * 18.00 / 100);
    decimal val = Convert.ToDecimal(string.Format("{0:F1}", price));
    price = decimal.ToDouble(val);
    return price;
}

Method Return type shouble be strictly double type and this method should always return 82.0 as double value not decimal. In the above code val is 82.0 but price is 82 which is not correct, output should be 82.0 after converting decimal to double because the method return type is double.


Solution

  • #1 - Don't use double to represent a currency value. The value of a double is an approximation, (see is floating point math broken). At some point you will run into rounding errors that you can't solve.

    #2 - string.Format is a terrible way to round a value. Use Math.Round.

    But to answer your question, there's no difference between 82f and 82.00000f. You get to choose how many digits to display when you convert the value to a string.

    While the decimal type does remember the number of significant digits. Meaning that there is a difference between 82m and 82.0000m at least when you convert to a string. double does not waste memory for this purpose.