开发者

Rounding a number

var output = Convert.ToDecimal(amount / 4);

labelOutput.Text = "You need: " + System.Math.Round(output,0);

this code开发者_JS百科 is part of a calculator for a game

"amount" is how much the user wants to make, and to make a single item, you need 4 pieces ( / 4)

for instance:

how much?: 20

20 / 4 = 5

"you need 5 pieces

but when i enter 21, still says 5 pieces but the users needs 6 pieces to make 21 items (4 for every item)

How can i round up the output to make it say 6 instead of 5 when the input is, in this case, 21 - 23?

(sorry if I didn't explain it good enough)


Use Math.Ceiling


To give a complete answer (combining the above):

  • Problem 1: You're doing integer division
  • Problem 2: You need to use Ceiling instead of Round

Assuming that amount is an integer, you need to have one of the values in your division operation be non-integral (either float/double or decimal, I've opted for decimal in my example with the m suffix). If both parts of the division operation are integral types, you'll get an integral answer (dropping the remainder).

You then call Ceiling to get the smallest integer value equal to or greater than output (rather than Round, which gives the closest integer value to output).

var output = amount / 4m;
labelOutput.Text = "You need: " + System.Math.Ceiling(output);


The round function rounds the number to the nearest one.

For a round up you have to use Math.Ceiling() If you need to round down you have to use Math.Floor()


var output = Math.Ceiling(amount / 4);


Assuming that 'amount' is an integer type, then the problem here is that you are a performing an integer (whole-number) division right in your first line.

Try changing the first line to: var output = Convert.ToDecimal(amount) / 4.0;


Round will round the number off -- what you want is to always round up, which you can get by using the Ceiling function


Use Math.Ceiling(amount / 4) instead.


A bit ugly, perhaps: var output = Convert.ToDecimal((amount+3) / 4); There's an edge case if your amount is right next to MaxValue where this code could break, depending on your denominator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜