Java中的双精度小数格式化

135

我遇到了一些格式化 double 类型小数的问题。如果我有一个 double 值,例如 4.0,如何格式化小数部分,使其变成 4.00?


1
尝试使用 String.format()java.text.Format - Code-Apprentice
1
可能是重复的问题:显示小数点后两位 - Raedwald
可能是将Double值格式化为2位小数的最佳方法的重复问题。 - Keale
14个回答

0

百分之百有效。

import java.text.DecimalFormat;

public class Formatting {

    public static void main(String[] args) {
        double value = 22.2323242434342;
        // or  value = Math.round(value*100) / 100.0;

        System.out.println("this is before formatting: "+value);
        DecimalFormat df = new DecimalFormat("####0.00");

        System.out.println("Value: " + df.format(value));
    }

}

-3

首先导入NumberFormat。然后添加以下内容:

NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

这将给你两位小数并在处理货币时加上美元符号。

import java.text.NumberFormat;
public class Payroll 
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
    int hoursWorked = 80;
    double hourlyPay = 15.52;

    double grossPay = hoursWorked * hourlyPay;
    NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();

    System.out.println("Your gross pay is " + currencyFormatter.format(grossPay));
    }

}

1
这个问题不是关于显示货币,更准确的答案是使用格式化函数(就像其他答案中所描述的)。 - Yacc

-4
您可以按照以下方式进行操作:
double d = 4.0;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

1
无法工作,因为它使用的是“##”而不是“00”。 - Joaquin Iurchuk

-4

我知道这是一个老话题,但如果你真的喜欢用句点而不是逗号,只需将结果保存为X,00到字符串中,然后简单地更改它为句点,这样你就得到了X.00

最简单的方法就是使用replace。

String var = "X,00";
String newVar = var.replace(",",".");

输出将是您想要的X.00。为了方便起见,您可以一次完成所有操作并将其保存到双精度变量中:

Double var = Double.parseDouble(("X,00").replace(",",".");

我知道现在这个回复可能没有用,但也许有人会在这个论坛上寻找像这样的快速解决方案。


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