将双精度数值保留两位小数

40

这应该很简单。我最初打算用JavaScript来完成,但必须在处理程序页设置之前完成它。无论如何,我需要使这些值保留两位小数。例如219333.5888888需要变成219333.58。是否有一个修剪函数或类似的东西?

 form.setUnitRepairCost(Double.toString(jobPlanBean.getUnitTotalCost()));   //UNIT REPAIR COST
 form.setUnitMaterialCost(Double.toString(jobPlanBean.getUnitTotalMaterialCost())); //UNIT MATERIAL COST

2
100,转换为整数,除以100.0? - Draco Ater
1
哈哈..这是第一个...不错。 - Doc Holiday
13个回答

66

这里是格式化十进制数值的简单示例

import java.text.*;

public class DecimalPlaces {

    public static void main(String[] args) {

        double d = 1.234567;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(d));
    }

}

2
如果您仍希望将数字作为double类型,那该怎么办?只需将其转换回去即可吗? - Michael K
嗯,实际上这并不起作用,因为DecimalFormat会进行四舍五入。API说:“DecimalFormat提供了在RoundingMode中定义的舍入模式以进行格式化。默认情况下,它使用RoundingMode.HALF_EVEN”。你需要更改舍入模式才能做到这一点。或者你可以将DecimalFormat增加一个小数位,然后在格式化后在字符串中截断它。糟糕。有没有什么不是临时修补的方法? - Michael K
14
为什么这是被接受的答案?原问题是“219333.5888888 需要变成 219333.58”.. 但是给出的解决方案(正如 @mikato 所写的)会得到 219333.59。需要将 DecimalFormat.setRoundingMode() 设置为 RoundingMode.FLOOR。 - phil
@phil 这只对正数有效,因为RoundingMode.FLOOR不会"截断"负数。对于219333.5888888,你会得到219333.58,正如OP所要求的,但是-219333.5888888会变成-219333.59。使用RoundingMode.DOWN,它总是朝0舍入(参见此处的表格)。 - undefined

18

将双倍乘以100.0并将其转换为int,然后将该int转换为double并除以100.0。

    int temp = (int)(longDouble*100.0);
    double shortDouble = ((double)temp)/100.0;

1
快速且易于记忆。 我的解决方案是 value = ((double)((int)(value *100.0)))/100.0; - Marco Fantasia

13
public static void main(String[] args) {

        double d = 6.3546;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(d));
}

9

为了获得一个双倍返回值而不是字符串:

double d = 80.123;
DecimalFormat df = new DecimalFormat("#.##");
double p = Double.parseDouble(df.format(d));

5
如何考虑:
new java.text.DecimalFormat("0.00").format( yourNumber );

或者是由TheStijn提供的链接。 - cjstehno

2

以下是将双精度值截断为两位小数的字符串操作。

public static String truncateUptoTwoDecimal(double doubleValue) {
    String value = String.valueOf(doubleValue);
    if (value != null) {
        String result = value;
        int decimalIndex = result.indexOf(".");
        if (decimalIndex != -1) {
            String decimalString = result.substring(decimalIndex + 1);
            if (decimalString.length() > 2) {
                result = value.substring(0, decimalIndex + 3);
            } else if (decimalString.length() == 1) {
                result = String.format(Locale.ENGLISH, "%.2f",
                        Double.parseDouble(value));
            }
        }
        return result;
    }
    return null;
}

1
很好的回答,因为其他方法没有明确说明小数点前的数字数量。 - Shridutt Kothari

2

正如其他人建议的那样,您可以使用java.text.DecimalFormat类的DecimalFormat。我们还可以使用DecimalFormat来四舍五入小数值。

例如:

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class DecimalDemo {

    private static DecimalFormat decimalFormatter = new DecimalFormat("#.##");

    public static void main(String[] args) {

        double number = 2.14159265359;
        System.out.println("Original Number : " + number);
        System.out.println("Upto 2 decimal : " + decimalFormatter.format(number));  //2.14

        // DecimalFormat, default is RoundingMode.HALF_EVEN
        decimalFormatter.setRoundingMode(RoundingMode.DOWN);
        System.out.println("Down : " + decimalFormatter.format(number));  //2.14

        decimalFormatter.setRoundingMode(RoundingMode.UP);
        System.out.println("Up : " + decimalFormatter.format(number));    //2.15

    }

}

1

考虑使用十进制格式:

DecimalFormat twoDForm = new DecimalFormat("#.##");


1
通过使用这两种方法,您可以处理所有异常:
private String convertedBalance(String balance){
    String convertedBalance = balance.toString();
    Double d;
    try {`enter code here`
        d = Double.parseDouble(balance.toString());
        Log.i("ConvertedNumber", "d (amount) = "+d.toString());
        d = round(d, 2);

        DecimalFormat f = new DecimalFormat("0.00");
        convertedBalance = f.format(d);

        Log.i("ConvertedNumber", "convertedBalance = "+convertedBalance);

    }catch (NumberFormatException e){
        Log.i("ConvertedNumber", "Number format exception");
    }

    return convertedBalance;
}


public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

0
您可以直接使用以下代码中的String.format()函数。
double height = 175.8653;
System.out.println("Height is: " + String.format("%.2f", height));

这将把双精度值截断为两位小数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接