Click here to Skip to main content
15,393,377 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I've read the article in how to round numbers. And I've basically made a little sum for the console to print out. This is the sum:

C#
int rndx = (int)Math.Round((decimal)(53 / 32), 0, MidpointRounding.AwayFromZero);
Console.WriteLine(rndx.ToString());


Everytime I run this code, it returns as 'one'. While it should be two.

I've even checked my calculator which says that 53 / 32 = 1,65625. Which would be rounded up to 2 since it's over number 'x.5'.

Any answers?
Posted

I expect it to return one! :laugh:

Why? Simples:

53 and 32 are integers. so 53 / 32 is also an integer, value 1.

The double cast of an integer value will not restore lost fractional data...
Try:
C#
int rndx = (int)Math.Round(((decimal)53 / (decimal)32), 0, MidpointRounding.AwayFromZero);

Or
C#
int rndx = (int)Math.Round((53M / 32M), 0, MidpointRounding.AwayFromZero);
Which specifies decimal constants.

[edit]Fingers-typing-ahead-of-brain disease. "double" for "decimal" :doh: - OriginalGriff[/edit]
   
v2
Comments
Deviant Sapphire 23-May-13 15:35pm
   
Silly me for forgetting that. Thank you very much.
OriginalGriff 23-May-13 15:37pm
   
You're welcome! (We all do it...)
Maciej Los 23-May-13 15:36pm
   
+5!
Math.Round[^] returns decimal value, not integer! Follow the link!

See other methods:
Math.Floor()[^]
Math.Ceiling()[^]
   
v2
Comments
OriginalGriff 23-May-13 15:35pm
   
It's simpler than that: integer / integer = integer :laugh:
Maciej Los 23-May-13 15:36pm
   
I see it ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900