peter
peter

Reputation: 8662

How to round a number

I have logic provided from excel as

CONCATENATE(ROUND(slno/256,0),ROUNDUP(((slno /256)-ROUND(slno/256,0))*256,0)) 

and i am converting in to c# the same.As per the logic if slno is 2696709 then answer should be 105345.But when i used following c# code i am getting it as 10534-2686169,how to correct and get it as 105345 Wrong code i used is as below

decimal slno = 2696709;
string result = Math.Round((slno / 256), 0).ToString() + 
                Math.Ceiling(((slno / 256) - 
                Math.Round((slno / 256), 0) * 256)).ToString();

Upvotes: 3

Views: 154

Answers (3)

Jonathon Chase
Jonathon Chase

Reputation: 9704

This is happening due to order of operations. Your multiplication by 256 is taking place before your subtraction.

In this portion of your code:

Math.Ceiling(((slno / 256) - Math.Round((slno / 256), 0) * 256))

You want to make the subtraction occur first, which you can do with parenthesis.

Math.Ceiling((((slno / 256) - Math.Round((slno / 256), 0)) * 256))

I would also look into setting an explicit MidpointRounding value on your rounding calls, as the default (to nearest even) is often not what you are expecting over away from zero. As an example, =ROUND(2.5,0) results in a cell with the value 3, Math.Round(2.5, 0) results in 2.

The complete translation of the excel formula could look like this:

decimal slno = 2696709; 
var val = slno / 256;
var valRound = Math.Round(val, 0, MidPointRounding.AwayFromZero);
var result = valRound.ToString() + Math.Ceiling((val - valRound) * 256).ToString();

Upvotes: 3

Zuhair
Zuhair

Reputation: 847

Thats the answer:

double slno = 2696709;
var result = Math.Round(slno / 256, 0).ToString() + Math.Ceiling(((slno / 256) - Math.Round(slno / 256, 0)) * 256).ToString();

Upvotes: 1

dana
dana

Reputation: 18135

I did a straight substitution of your formula...

  • CONCATENATE => String.Concat
  • ROUND => Math.Round
  • ROUNDUP => Math.Ceiling

Also, I switched to using using AwayFromZero MidpointRounding as I beleive it is the Excel default, whereas .NET defaults to ToEven.

decimal slno = 2696709;
string result = String.Concat(
        Math.Round(slno/256,MidpointRounding.AwayFromZero),
        Math.Ceiling(((slno /256)-Math.Round(slno/256,MidpointRounding.AwayFromZero))*256)
    );

Upvotes: 2

Related Questions