2012-05-31 71 views
0

我正在编写一个程序,使用缝和SQL数据库,存储有关员工的信息。我被告知将数据存储在数据库中。当用户输入薪水时,它被存储为一个字符串,当我使用员工对象的setter时,它将它变成一个int。我的问题是,我无法弄清楚如何将它重新存回字符串中,并保留小数点。有任何想法吗?使用整数货币

+5

'int'应该是“美分数”,不是? –

+0

是的。 int将是浮点数* 100 – user1423793

回答

0

如果存储为美分的数字,它格式化为float然后再乘以100

+1

这将导致舍入错误。 –

+0

我会使用双精度(15位数的精度)而不是浮点数(精度为6位数) –

2

最简单的事情把它即会绝对是一般工作,可能是

BigDecimal.valueOf(cents).scaleByPowerOfTen(-2).toString(); 

(这有一个优势,推广longBigInteger数字美分,捏)

另一种解决方案,肯定会工作,虽然它会稍微复杂一些,会沿着这条线

return Integer.toString(cents/100) 
    + "." 
    + new DecimalFormat("00").format(cents % 100); 
0

你可以使用类似的东西。

int priceInCents = ... 
String price = String.format("%.2f", priceInCents/100.0); 
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); 
    } 
} 
+0

谢谢各位的回复。我已经明白了。 – user1423793