如何在Java中四舍五入到小数点后两位?

时间:2021-12-28 08:35:38

This is what I did to round a double to 2 decimal places:

这是我对小数点后两位进行的四舍五入:

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0! What I want is both rounding as well as formatting to 2 decimal places.

如果amount = 25.3569或类似的东西,这很好,但如果amount = 25.00或amount = 25.0,则得到25.0!我想要的是舍入和格式化到小数点后两位。

20 个解决方案

#1


20  

Are you working with money? Creating a String and then converting it back is pretty loopy.

你是拿钱工作吗?创建一个字符串,然后再将其转换回原来的格式,这是非常愚蠢的。

Use BigDecimal. This has been discussed quite extensively. You should have a Money class and the amount should be a BigDecimal.

使用BigDecimal。这已经被广泛地讨论过了。你应该有一个货币类,金额应该是一个大十进制数。

Even if you're not working with money, consider BigDecimal.

即使你不用钱,也可以考虑使用BigDecimal。

#2


47  

Just use: (easy as pie)

只需使用:(简单如馅饼)

double number = 651.5176515121351;

number = Math.round(number * 100);
number = number/100;

The output will be 651.52

输出是651.52

#3


19  

Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:

使用数字位保持器(0),如'#'尾随/前导0显示为无:

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

#4


10  

You can't 'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with binary fractional places.

你不能“四舍五入到小数点后”,因为双打没有小数点。你可以把一个双精度浮点数转换成一个有N个小数位数的基数-10字符串,因为base-10确实有小数点,但是当你把它转换回去时,你又回到了双精度浮点数的双精度浮点数。

#5


5  

This is the simplest i could make it but it gets the job done a lot easier than most examples ive seen.

这是我能做到的最简单的方法,但它比我见过的大多数例子要容易得多。

    double total = 1.4563;

    total = Math.round(total * 100);

    System.out.println(total / 100);

The result is 1.46.

结果是1.46。

#6


4  

You can use org.apache.commons.math.util.MathUtils from apache common

您可以使用apache common中的org.apache.common .math.util. mathutils

double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);

双圆= MathUtils。轮(double1 2 BigDecimal.ROUND_HALF_DOWN);

#7


4  

Use this

使用这个

String.format("%.2f", doubleValue) // change 2, according to your requirement.

String.format(“%。2f",双值)// /变更2,根据您的要求。

#8


2  

You can use Apache Commons Math:

您可以使用Apache Commons Math:

Precision.round(double x, int scale)

source: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html#round(double,%20int)

来源:http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html轮(双% 20 int)

#9


1  

Your Money class could be represented as a subclass of Long or having a member representing the money value as a native long. Then when assigning values to your money instantiations, you will always be storing values that are actually REAL money values. You simply output your Money object (via your Money's overridden toString() method) with the appropriate formatting. e.g $1.25 in a Money object's internal representation is 125. You represent the money as cents, or pence or whatever the minimum denomination in the currency you are sealing with is ... then format it on output. No you can NEVER store an 'illegal' money value, like say $1.257.

您的货币类可以表示为Long的子类,或者有一个成员表示货币值为本机Long。然后,当为您的货币实例化赋值时,您将始终存储实际货币值的值。您只需使用适当的格式输出您的Money对象(通过您的Money的重写toString()方法)。e。货币对象的内部表示是125克。你把钱表示为美分,或便士,或者任何你所封印的货币的最小面额。然后格式化输出。不,你永远不能储存“非法”的货币价值,比如1.257美元。

#10


1  

double amount = 25.00;

双数量= 25.00;

NumberFormat formatter = new DecimalFormat("#0.00");

NumberFormat formatter = new DecimalFormat(“#0.00”);

System.out.println(formatter.format(amount));

System.out.println(formatter.format(数量);

#11


1  

DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);

#12


0  

If you want the result to two decimal places you can do

如果你想要结果小数点后两位,你可以这样做

// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0; 

This result is not precise but Double.toString(double) will correct for this and print one to two decimal places. However as soon as you perform another calculation, you can get a result which will not be implicitly rounded. ;)

这个结果不是精确的,而是双重的。tostring (double)将纠正这个错误,并打印1到2位小数。然而,一旦您执行另一个计算,您就可以得到一个不会隐式四舍五入的结果。,)

#13


0  

Math.round is one answer,

数学。圆是一个答案,

public class Util {
 public static Double formatDouble(Double valueToFormat) {
    long rounded = Math.round(valueToFormat*100);
    return rounded/100.0;
 }
}

Test in Spock,Groovy

void "test double format"(){
    given:
         Double performance = 0.6666666666666666
    when:
        Double formattedPerformance = Util.formatDouble(performance)
        println "######################## formatted ######################### => ${formattedPerformance}"
    then:
        0.67 == formattedPerformance

}

#14


0  

Presuming the amount could be positive as well as negative, rounding to two decimal places may use the following piece of code snippet.

假设数量可以是正数,也可以是负数,四舍五入到小数点后两位可以使用下面的代码片段。

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    if (d < 0)
       d -= 0.005;
    else if (d > 0)
       d += 0.005;
    return (double)((long)(d * 100.0))/100);
}

#15


0  

Starting java 1.8 you can do more with lambda expressions & checks for null. Also, one below can handle Float or Double & variable number of decimal points (including 2 :-)).

从java 1.8开始,您可以使用lambda表达式和检查null。此外,下面的一个可以处理浮点数或双和可变小数(包括2:-)。

public static Double round(Number src, int decimalPlaces) {

    return Optional.ofNullable(src)
            .map(Number::doubleValue)
            .map(BigDecimal::new)
            .map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
            .map(BigDecimal::doubleValue)
            .orElse(null);
}

#16


0  

where num is the double number

num是双号?

  • Integer 2 denotes the number of decimal places that we want to print.
  • 整数2表示要打印的小数位数。
  • Here we are taking 2 decimal palces

    这里取2个小数点

    System.out.printf("%.2f",num);

    System.out.printf(“% .2f”,num);

#17


0  

You can try this one:

你可以试试这个:

public static String getRoundedValue(Double value, String format) {
    DecimalFormat df;
    if(format == null)
        df = new DecimalFormat("#.00");
    else 
        df = new DecimalFormat(format);
    return df.format(value);
}

or

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

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

#18


0  

Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:

这里有一个简单的方法可以保证输出四舍五入到小数点后两位的fixmyednumber:

import java.text.DecimalFormat;

public class TwoDecimalPlaces {
    static double myFixedNumber = 98765.4321;
    public static void main(String[] args) {

        System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
    }
}

The result is: 98765.43

结果是:98765.43

#19


0  

    int i = 180;
    int j = 1;
    double div=  ((double)(j*100)/i);
    DecimalFormat df = new DecimalFormat("#.00"); // simple way to format till any deciaml points
    System.out.println(div);
    System.out.println(df.format(div));

#20


0  

First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.

首先声明一个DecimalFormat类的对象。注意,DecimalFormat中的参数是#。00也就是小数点后两位。

private static DecimalFormat df2 = new DecimalFormat("#.00");

Now, apply the format to your double value:

现在,将格式应用到您的双值:

double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12

Note in case of double input = 32.1;

双输入时的注意事项= 32.1;

Then the output would be 32.10 and so on.

然后输出是32。10,以此类推。

#1


20  

Are you working with money? Creating a String and then converting it back is pretty loopy.

你是拿钱工作吗?创建一个字符串,然后再将其转换回原来的格式,这是非常愚蠢的。

Use BigDecimal. This has been discussed quite extensively. You should have a Money class and the amount should be a BigDecimal.

使用BigDecimal。这已经被广泛地讨论过了。你应该有一个货币类,金额应该是一个大十进制数。

Even if you're not working with money, consider BigDecimal.

即使你不用钱,也可以考虑使用BigDecimal。

#2


47  

Just use: (easy as pie)

只需使用:(简单如馅饼)

double number = 651.5176515121351;

number = Math.round(number * 100);
number = number/100;

The output will be 651.52

输出是651.52

#3


19  

Use a digit place holder (0), as with '#' trailing/leading zeros show as absent:

使用数字位保持器(0),如'#'尾随/前导0显示为无:

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

#4


10  

You can't 'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with binary fractional places.

你不能“四舍五入到小数点后”,因为双打没有小数点。你可以把一个双精度浮点数转换成一个有N个小数位数的基数-10字符串,因为base-10确实有小数点,但是当你把它转换回去时,你又回到了双精度浮点数的双精度浮点数。

#5


5  

This is the simplest i could make it but it gets the job done a lot easier than most examples ive seen.

这是我能做到的最简单的方法,但它比我见过的大多数例子要容易得多。

    double total = 1.4563;

    total = Math.round(total * 100);

    System.out.println(total / 100);

The result is 1.46.

结果是1.46。

#6


4  

You can use org.apache.commons.math.util.MathUtils from apache common

您可以使用apache common中的org.apache.common .math.util. mathutils

double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);

双圆= MathUtils。轮(double1 2 BigDecimal.ROUND_HALF_DOWN);

#7


4  

Use this

使用这个

String.format("%.2f", doubleValue) // change 2, according to your requirement.

String.format(“%。2f",双值)// /变更2,根据您的要求。

#8


2  

You can use Apache Commons Math:

您可以使用Apache Commons Math:

Precision.round(double x, int scale)

source: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html#round(double,%20int)

来源:http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html轮(双% 20 int)

#9


1  

Your Money class could be represented as a subclass of Long or having a member representing the money value as a native long. Then when assigning values to your money instantiations, you will always be storing values that are actually REAL money values. You simply output your Money object (via your Money's overridden toString() method) with the appropriate formatting. e.g $1.25 in a Money object's internal representation is 125. You represent the money as cents, or pence or whatever the minimum denomination in the currency you are sealing with is ... then format it on output. No you can NEVER store an 'illegal' money value, like say $1.257.

您的货币类可以表示为Long的子类,或者有一个成员表示货币值为本机Long。然后,当为您的货币实例化赋值时,您将始终存储实际货币值的值。您只需使用适当的格式输出您的Money对象(通过您的Money的重写toString()方法)。e。货币对象的内部表示是125克。你把钱表示为美分,或便士,或者任何你所封印的货币的最小面额。然后格式化输出。不,你永远不能储存“非法”的货币价值,比如1.257美元。

#10


1  

double amount = 25.00;

双数量= 25.00;

NumberFormat formatter = new DecimalFormat("#0.00");

NumberFormat formatter = new DecimalFormat(“#0.00”);

System.out.println(formatter.format(amount));

System.out.println(formatter.format(数量);

#11


1  

DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);

#12


0  

If you want the result to two decimal places you can do

如果你想要结果小数点后两位,你可以这样做

// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0; 

This result is not precise but Double.toString(double) will correct for this and print one to two decimal places. However as soon as you perform another calculation, you can get a result which will not be implicitly rounded. ;)

这个结果不是精确的,而是双重的。tostring (double)将纠正这个错误,并打印1到2位小数。然而,一旦您执行另一个计算,您就可以得到一个不会隐式四舍五入的结果。,)

#13


0  

Math.round is one answer,

数学。圆是一个答案,

public class Util {
 public static Double formatDouble(Double valueToFormat) {
    long rounded = Math.round(valueToFormat*100);
    return rounded/100.0;
 }
}

Test in Spock,Groovy

void "test double format"(){
    given:
         Double performance = 0.6666666666666666
    when:
        Double formattedPerformance = Util.formatDouble(performance)
        println "######################## formatted ######################### => ${formattedPerformance}"
    then:
        0.67 == formattedPerformance

}

#14


0  

Presuming the amount could be positive as well as negative, rounding to two decimal places may use the following piece of code snippet.

假设数量可以是正数,也可以是负数,四舍五入到小数点后两位可以使用下面的代码片段。

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    if (d < 0)
       d -= 0.005;
    else if (d > 0)
       d += 0.005;
    return (double)((long)(d * 100.0))/100);
}

#15


0  

Starting java 1.8 you can do more with lambda expressions & checks for null. Also, one below can handle Float or Double & variable number of decimal points (including 2 :-)).

从java 1.8开始,您可以使用lambda表达式和检查null。此外,下面的一个可以处理浮点数或双和可变小数(包括2:-)。

public static Double round(Number src, int decimalPlaces) {

    return Optional.ofNullable(src)
            .map(Number::doubleValue)
            .map(BigDecimal::new)
            .map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
            .map(BigDecimal::doubleValue)
            .orElse(null);
}

#16


0  

where num is the double number

num是双号?

  • Integer 2 denotes the number of decimal places that we want to print.
  • 整数2表示要打印的小数位数。
  • Here we are taking 2 decimal palces

    这里取2个小数点

    System.out.printf("%.2f",num);

    System.out.printf(“% .2f”,num);

#17


0  

You can try this one:

你可以试试这个:

public static String getRoundedValue(Double value, String format) {
    DecimalFormat df;
    if(format == null)
        df = new DecimalFormat("#.00");
    else 
        df = new DecimalFormat(format);
    return df.format(value);
}

or

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

    long factor = (long) Math.pow(10, places);
    value = value * factor;
    long tmp = Math.round(value);
    return (double) tmp / factor;
}

#18


0  

Here is an easy way that guarantee to output the myFixedNumber rounded to two decimal places:

这里有一个简单的方法可以保证输出四舍五入到小数点后两位的fixmyednumber:

import java.text.DecimalFormat;

public class TwoDecimalPlaces {
    static double myFixedNumber = 98765.4321;
    public static void main(String[] args) {

        System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
    }
}

The result is: 98765.43

结果是:98765.43

#19


0  

    int i = 180;
    int j = 1;
    double div=  ((double)(j*100)/i);
    DecimalFormat df = new DecimalFormat("#.00"); // simple way to format till any deciaml points
    System.out.println(div);
    System.out.println(df.format(div));

#20


0  

First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.

首先声明一个DecimalFormat类的对象。注意,DecimalFormat中的参数是#。00也就是小数点后两位。

private static DecimalFormat df2 = new DecimalFormat("#.00");

Now, apply the format to your double value:

现在,将格式应用到您的双值:

double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12

Note in case of double input = 32.1;

双输入时的注意事项= 32.1;

Then the output would be 32.10 and so on.

然后输出是32。10,以此类推。