Java四舍五入保留两位小数

2023年5月8日11:07:23

Java四舍五入保留两位小数

一、前言

环境

  • 开发工具:IntelliJ IDEA
  • JDK:1.8

BigDecimal:https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html

DecimalFormat:https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

Math:https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html

apache commons-math:https://commons.apache.org/proper/commons-math/

maven repository:https://mvnrepository.com/

二、正文

BigDecimal

  • RoundingMode
算法 说明
ROUND_UP 舍入模式从零舍入
ROUND_DOWN 舍入模式向零舍入
ROUND_CEILING 舍入模式向正无穷大舍入
ROUND_FLOOR 舍入模式向负无穷大舍入
HALF_UP 舍入模式向“最近的邻居”舍入,除非两个邻居是等距的,在这种情况下向上舍入
HALF_DOWN 舍入模式向“最近的邻居”舍入,除非两个邻居是等距的,在这种情况下向下舍入
HAIL_EVEN 舍入模式向“最近的邻居”舍入,除非两个邻居是等距的,在这种情况下,向偶数邻居舍入
UNNECESSARY 舍入模式断言所请求的操作具有精确的结果,因此不需要舍入
  • 代码
double num = 3333.445555;
// BigDecimal
BigDecimal bigDecimal = new BigDecimal(num);
bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);
System.out.println("bigDecimal="+ bigDecimal.doubleValue());

DecimalFormat

double num = 3333.445555;
// DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("#.##");
String numByDF = decimalFormat.format(num);
System.out.println("decimalFormat="+ numByDF);

Math

double num = 3333.445555;
// Math
double numByM = Math.round(num*100.0) / 100.0;
System.out.println("numByM="+ numByM);

commons-math3

  • maven 依赖
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.6.1</version>
</dependency>
  • 代码
double num = 3333.445555;
// commons-math3
double numByM3 = Precision.round(num, 2);
System.out.println("numByM3="+ numByM3);

String#format

double num = 3333.445555;
// String#format
String numByStr = String.format("%.2f", num);
System.out.println("String.format="+ numByStr);

  • 作者:JotaX
  • 原文链接:https://blog.csdn.net/u011424614/article/details/123276105
    更新时间:2023年5月8日11:07:23 ,共 1629 字。