有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将整数格式化为两个小数?

Possible Duplicate:
How to format an integer to have two decimals?

我正在努力处理这段代码

DecimalFormat df = new DecimalFormat("00.##");
df.setMinimumFractionDigits(2);
return df.format(Integer.valueOf(amount));

我需要的是:

Input: 2, Output: 2.00

Input 20, Output: 20,00

Input 1003, Output: 100,30

Input 120323, Output: 1.203,23 (a thousand two hundred and three and twenty three cents)

我不能使用DecimalFormat,因为我没有模式“example.”

我应该总是有两个小数。如果金额小于100,那么我只需要取金额本身并加上“.00”,如果它大于100,意味着最后两位数字是我需要的两位小数。它们是美分

有人能帮我吗


共 (2) 个答案

  1. # 1 楼答案

    如果你想加两位小数(总是^{),这有点多余

    return String.format("%.2f", amount > 100 ? amount/100.0 : (double) amount);
    

    我建议你保留一套装置。你应该可以随时使用美分。如果你不这样做,你可能会感到困惑。例如,100和10000都是100.00

  2. # 2 楼答案

    If the amount is less that 100, then I only have to take the amount itself and add ".00" If it is bigger than 100, means that the two last digits are the two decimals I need.

    首先你需要解决这个问题。一个类或一个本机类型应该只包含一种数据,而不应该在其他类或代码中添加关于如何根据情况处理该数据的详细知识

    让它返回所有情况下的便士数,或者让它返回支持小数点的数字。更好的解决方案是分币数

    这样你就不必在格式中加入逻辑,当你第二次需要格式化同样的东西时,它肯定不会出现