I'm writing a program, using seam and an SQL database, that stores information about employees. I was told to store the pay as ints in the database. When the user enters the pay, it is stored as a String and when I use a setter for the employee object it turns it into an int. My problem is that I can't figure out how to store it back in the string with the decimal back in place. Any ideas?
Asked
Active
Viewed 1,459 times
0
-
5The `int` should be "the number of cents," no? – Louis Wasserman May 31 '12 at 12:56
-
Yes. The int would be the floating point number * 100 – user1423793 May 31 '12 at 13:00
4 Answers
3
The simplest thing that will definitely work in general is probably
BigDecimal.valueOf(cents).scaleByPowerOfTen(-2).toString();
(This has the advantage of generalizing to long
or BigInteger
numbers of cents, in a pinch.)
The other solution that would definitely work, although it's slightly more complicated, would be something along the lines of
return Integer.toString(cents / 100)
+ "."
+ new DecimalFormat("00").format(cents % 100);

Louis Wasserman
- 191,574
- 25
- 345
- 413
0
if it is stored as number of cents, format it to a float
and then divide it by 100.

Tikkes
- 4,599
- 4
- 36
- 62
-
I would use double (15 digits of accuracy) rather than float (6 digits of accuracy) – Peter Lawrey May 31 '12 at 13:02
-
It's very bad idea to use float or double for monetary calculations because you could lose precision! Please read this article about this problem - https://dzone.com/articles/never-use-float-and-double-for-monetary-calculatio – SavinI Jan 24 '20 at 04:47
0
You can use something like.
int priceInCents = ...
String price = String.format("%.2f", priceInCents / 100.0);

Peter Lawrey
- 525,659
- 79
- 751
- 1,130
0
Would something like this be what you are looking for?
class Currency {
int cents;
public Currency(int cents) {
this.cents = cents;
}
public Currency(String cents) {
this(Integer.parseInt(cents));
}
public int getCents(){
return cents;
}
public double getValue(){
return cents/100.0d;
}
private static final DecimalFormat o = new DecimalFormat("0");
private static final DecimalFormat oo = new DecimalFormat("00");
@Override
public String toString() {
return o.format(cents / 100) + "." + oo.format(cents % 100);
}
}

OldCurmudgeon
- 64,482
- 16
- 119
- 213