Java 对货币使用整数
我正在使用seam和SQL数据库编写一个程序,用于存储有关员工的信息。我被告知将支付方式INT存储在数据库中。当用户输入pay时,它被存储为一个字符串,当我对employee对象使用setter时,它会将其转换为int。我的问题是,我不知道如何将它存储回字符串中,并将小数点放回原位。有什么想法吗?如果以美分的形式存储,则将其格式化为Java 对货币使用整数,java,int,seam,currency,Java,Int,Seam,Currency,我正在使用seam和SQL数据库编写一个程序,用于存储有关员工的信息。我被告知将支付方式INT存储在数据库中。当用户输入pay时,它被存储为一个字符串,当我对employee对象使用setter时,它会将其转换为int。我的问题是,我不知道如何将它存储回字符串中,并将小数点放回原位。有什么想法吗?如果以美分的形式存储,则将其格式化为浮点值,然后除以100。如果以美分的形式存储,则将其格式化为浮点值,然后除以100。通常最简单的方法可能是 BigDecimal.valueOf(cents).sca
浮点值,然后除以100。如果以美分的形式存储,则将其格式化为浮点值,然后除以100。通常最简单的方法可能是
BigDecimal.valueOf(cents).scaleByPowerOfTen(-2).toString();
(这有一个优点,即在必要时可以推广到long
或biginger
美分数。)
另一个肯定有效的解决方案,虽然稍微复杂一点,但应该是类似于
return Integer.toString(cents / 100)
+ "."
+ new DecimalFormat("00").format(cents % 100);
一般来说,最简单的肯定有效的方法是
BigDecimal.valueOf(cents).scaleByPowerOfTen(-2).toString();
(这有一个优点,即在必要时可以推广到long
或biginger
美分数。)
另一个肯定有效的解决方案,虽然稍微复杂一点,但应该是类似于
return Integer.toString(cents / 100)
+ "."
+ new DecimalFormat("00").format(cents % 100);
你可以用类似的东西
int priceInCents = ...
String price = String.format("%.2f", priceInCents / 100.0);
你可以用类似的东西
int priceInCents = ...
String price = String.format("%.2f", priceInCents / 100.0);
像这样的东西是你想要的吗
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);
}
}
像这样的东西是你想要的吗
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);
}
}
int
应该是“美分数”,否?是。int应该是浮点数*100,int
应该是“美分数”,否?是。int将是浮点数*100I将使用双精度(精度为15位)而不是浮点数(精度为6位)。使用浮点数或双精度进行货币计算是非常糟糕的,因为可能会失去精度!请阅读这篇关于这个问题的文章-我会使用双精度(15位精度)而不是浮点数(6位精度)。使用浮点数或双精度进行货币计算是一个非常糟糕的主意,因为你可能会失去精度!请阅读这篇关于这个问题的文章,谢谢你们的回复。我现在明白了。谢谢你们的回复。我现在已经弄明白了。