1

I need to round up a number to 4 decimal places.

This answer does not help, because the method:

    public static decimal RoundUp(this decimal input, int places)
    {
        decimal multiplier = Convert.ToDecimal(Math.Pow(10, Convert.ToDouble(places)));
        return Math.Ceiling(input * multiplier) / multiplier;
    }

will round up number 1.12333 to 1.1234 (as expected), but 1.123304 will be rounded up to 1.1233 and I need it to be 1.1234 too.

Community
  • 1
  • 1
alegz
  • 133
  • 1
  • 13

1 Answers1

1

The method you posted works. Most likely, you're working with incorrect data types or are having different values than you think. Sample code:

RoundUp(1.123304M, 4) // 1.1234

Note the M after the literal - this denotes the number as a decimal literal, rather than double. However, no matter what I do, I can't replicate your result anyway, so you most likely simply don't have the value you think you have. Keep everything in decimals, and you'll be fine. Note that for large values of places, you might need to make your own Math.Pow function - or just make a quick lookup table for the values you're actually using (e.g. 10000 in your example).

Luaan
  • 62,244
  • 7
  • 97
  • 116
  • You are right, it works. i must have made some mistake. Is there a way to delete this question? – alegz Jun 30 '16 at 13:44
  • Right under the tags, there's a `delete` link (sadly, it doesn't *appear* to be a link - a bit ironic considering it's one of the UX "bad things to do" Joel mentions in his UX book :P). – Luaan Jun 30 '16 at 13:46