Round currency

G

Guest

Hi

Have a method that rounds a currency value to the closest quarter. It works
fine as long as the value is above zero, below zero it rounds to the upper
integer. Any working solution is much appreciated.

protected void Page_Load(object sender, EventArgs e)
{
double d1 = 2.73d;
Response.Write(LevelCurrency(d1).ToString("c")); //Correct

Response.Write("<br/>");

double d2 = -2.73d;
Response.Write(LevelCurrency(d2).ToString("c"));//Incorrect
}

private double LevelCurrency(double price)
{
int totalcost = (int)price;
double d = price - totalcost;
if (d < 0.25d)
return (double)totalcost;

if (d > 0.74d)
return (double)(++totalcost);

return (double)(totalcost + 0.5);
}
 
F

Fredo

Not really sure what your code is doing, but I would do it something like
this:

private double LevelCurrency(double price)
{
int totalcost = (int) price * 4;
return ((double) totalCost / 4.0);
}

This should round to a quarter. You might have to do a check to see if the
value is less than 0 and handle it separate there, though.

Fredo
 
J

Jesse Houwing

* Senna wrote, On 19-7-2006 23:44:
Hi

Have a method that rounds a currency value to the closest quarter. It works
fine as long as the value is above zero, below zero it rounds to the upper
integer. Any working solution is much appreciated.

protected void Page_Load(object sender, EventArgs e)
{
double d1 = 2.73d;
Response.Write(LevelCurrency(d1).ToString("c")); //Correct

Response.Write("<br/>");

double d2 = -2.73d;
Response.Write(LevelCurrency(d2).ToString("c"));//Incorrect
}

private double LevelCurrency(double price)
{
int totalcost = (int)price;
double d = price - totalcost;
if (d < 0.25d)
return (double)totalcost;

if (d > 0.74d)
return (double)(++totalcost);

return (double)(totalcost + 0.5);
}

First, you should probably not use a double to hold a currency value, as
doubles have problems with broken amounts and precision. Decimal or
Money types are a better choice. See the MSDN manual for a completer
explanation.

Apart from that I guess you're being bitten by Bankers rounding. .Net
uses this type of rounding, because in the long run it's more honest to
round up and down an even amount of times. This will cause certain
values to be rounded up and other rounded down.

For an explanation on different rounding strategies look here:
http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189

Jesse Houwing
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top