12,698,775 members (23,823 online)
Technical Blog
alternative version

7.4K views
4 bookmarked
Posted

# Round Up A Number to the Greatest 10s Place

, 24 Jul 2014 CPOL
 Rate this:
How to round up a number to the greatest 10s place

Recently, we faced a situation in which we need to round up a number to the greatest 10s place.

For example: we needed to round up a number as follows:

• 1023     -> 2000
• 37911   -> 40000
• 912345 -> 1000000

First, we checked Math.Round(). But it didn’t solve our problem. `Math.Round()` supports only rounding a value to the nearest integer or to the specified number of fractional digits. On further checking, we come up with a solution by using Math.Ceiling() method.

`Math.Ceiling() `returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.

For example:

• `Math.Ceiling(7.3)`   -> 8
• `Math.Ceiling(7.64)` -> 8
• `Math.Ceiling(0.12)` -> 1

Below is the solution we came up with:

```decimal[] values = { 1023, 37911, 23000, 1234, 912345 };
foreach (var value in values) {
//// get the length of the 10s places;
var length = value.ToString().Length - 1;
//// using Math.Pow() calculate the power of 10s
var power = Math.Pow(10, (double)length);
//// var roundadValue = Math.Ceiling(1023 / 1000) * 1000;
var roundadValue = Math.Ceiling(value / (decimal)power) * (decimal)power;

}```

## The Logic

```Math.Ceiling(value / (decimal)power) * (decimal)power;
var roundadValue = Math.Ceiling(1023 / 1000) * 1000;```

So, for any number, first calculate the power of 10s and then use it for the above calculation to get the results.

## Share

 Technical Lead Eyepax IT Consulting (Pvt) Ltd. Sri Lanka
Having more than 9 year hands-on industry experience in software development
Responsible for designing, implementing and managing complex software systems with stringent up-time requirement.

Visit my blog

## You may also be interested in...

 Pro Pro

 First Prev Next
 Situation NOT Citation deebee++23-Jul-14 4:27 deebee++ 23-Jul-14 4:27
 Re: Situation NOT Citation Tharaka MTR23-Jul-14 22:53 Tharaka MTR 23-Jul-14 22:53
 Re: Nice solution, but Tharaka MTR22-Jul-14 7:02 Tharaka MTR 22-Jul-14 7:02
 Re: Nice solution, but George Swan22-Jul-14 11:41 George Swan 22-Jul-14 11:41
 Re: Nice solution, but Tomas Ruksenas18-Aug-14 4:57 Tomas Ruksenas 18-Aug-14 4:57
 Last Visit: 31-Dec-99 19:00     Last Update: 21-Jan-17 23:23 Refresh 1