Java – double / float値を小数点以下2桁に丸める方法
Javaでは、floatまたはdoubleを小数点以下2桁に丸める方法がいくつかあります。
Note
これを読むRoundingMode
1. DecimalFormat
DecimalExample.java
package com.example;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalExample {
private static DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
double input = 1205.6358;
System.out.println("salary : " + input);
// DecimalFormat, default is RoundingMode.HALF_EVEN
System.out.println("salary : " + df.format(input)); //1205.64
df.setRoundingMode(RoundingMode.DOWN);
System.out.println("salary : " + df.format(input)); //1205.63
df.setRoundingMode(RoundingMode.UP);
System.out.println("salary : " + df.format(input)); //1205.64
}
}
出力
salary : 1205.6358 salary : 1205.64 salary : 1205.63 salary : 1205.64
2. BigDecimal
BigDecimalExample.java
package com.example;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalExample {
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
BigDecimal bd = new BigDecimal(input).setScale(2, RoundingMode.HALF_UP);
double salary = bd.doubleValue();
System.out.println("salary : " + salary);
}
}
出力
salary : 1205.6358 salary : 1205.64
3. Math.round
MathExample.java
package com.example;
public class MathExample {
public static void main(String[] args) {
double input = 1205.6358;
System.out.println("salary : " + input);
double salary = Math.round(input * 100.0) / 100.0;
System.out.println("salary : " + salary);
}
}
出力
salary : 1205.6358 salary : 1205.64
説明、アカデミーの目的で、小数点以下3桁、*1000
input = 1205.6358; Math.round(input * 100.0) / 100.0; Math.round(120563.58) / 100.0; 120564 / 100.0; salary = 1205.64