CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Java and JSP (http://www.codingforums.com/forumdisplay.php?f=54)
-   -   Converting pence into pounds help (http://www.codingforums.com/showthread.php?t=284251)

abell12 12-16-2012 06:47 PM

Converting pence into pounds help
 
I want to convert a pence value to pounds.
So I have something like this:

Code:

   
public double toPounds()
{
int itemPrice = 256;   
int pounds = itemPrice / 100;
int pence = itemPrice % 100;
return pounds + pence;
}

The int pounds works returning the value 2.0 for the 2 pounds.
But its the pence im stuck on.
Can anyone help me out.

Thanks in advance.

Fou-Lu 12-16-2012 07:01 PM

So pence is like 1 cent, and a pound is 100 cents?
The problem here is that you should end up with 58. The reason is that 256 % 100 is 56, and 256 / 100 (as integer) is 2.
So up to the return the values are still good to work with. You have pounds as 2 and pence as 56. Its the addition that you need to modify (as one of the several approaches), and you can simply return pounds + (pence / 100.0); as your return value. That should work as it will convert 56 to 0.56 which it then adds to the 2.0 (which is actually just 2, but that should be fine).
Ultimately, if its just 100 pence per pound, then you can simply return itemPrice / 100;. You'll want to use a money formatter to constrain it to the 2 significant digits (with 100 as the divisor you could end up with only 1 significant digit, but I don't think you can end up with 3+ significant digits).

abell12 12-16-2012 07:07 PM

Thanks so much it works.
Yes pence is like 1 cent, and a pound is 100 cents, either way you got the idea.


All times are GMT +1. The time now is 09:02 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.