Round to the next higher number

13,467

Solution 1

How about Math.Ceiling(v / 2.5) * 2.5 ?

Solution 2

You need Math.Ceiling

This takes a double and rounds it upwards to the nearest integer, unless the value is already equal to an integer. The datatype it returns is still a double, however.

Usage example...

Double testValue = 1.52;
Console.WriteLine(Math.Ceiling(testValue));

... would print 2.

Solution 3

Math.Ceiling does exactly what you need.

Solution 4

you can use Math.Ceiling for that

Share:
13,467
dannyyy
Author by

dannyyy

Updated on August 04, 2022

Comments

  • dannyyy
    dannyyy over 1 year

    I want to round a value (double) to the next (allways round up) number. Rounding can be defined by any number.

    Exp.:
    Round up to the next 2.50

    0.00       --> 0.00
    0.01       --> 2.50
    2.49       --> 2.50
    2.50       --> 2.50
    2.50000001 --> 5.00
    ...
    

    The algorithm to do this is easy (if 'number' was negative * -1):

    Math.Round((Math.Abs(number) + tolerance) / 2.50, MidpointRounding.AwayFromZero) * 2.50
    

    Tolerance is defined like this:

    tolerance = 2.50 / 2 - Math.Pos(10, -x);
    

    But I don't know how to determine x! Because in case of the 1st-4th example x should be 0.01 in case of the 5th example it should be 0.0000001 and so on...

    Search results only suggest to parse the string of a decimal number and count the decimal digit. Is there no mathematical way? Otherwise I have to treat with different locale settings for decimal seperator and numbers with no decimal digits (no decimal seperator to remove).

    May anyone has a solution for my issue. Thank you!

    Kind regards, Danny

  • dannyyy
    dannyyy over 12 years
    just too simple ;) Thank you!
  • slugster
    slugster over 11 years
    Good stuff :) This answer came up in the low quality review queue due to it only being a link answer, your edit should bump it out of the queue now.