欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java中常见的几种四舍五入方法总结,

来源: javaer 分享于  点击 21117 次 点评:271

Java中常见的几种四舍五入方法总结,


目录
  • 1. 使用Math.round()方法
  • 2. 使用BigDecimal类
  • 3. 使用String.format()方法
  • 4. 使用DecimalFormat类
  • 总结

在Java中,四舍五入到特定的小数位数是一个常见的需求,可以通过多种方式实现。以下是几种常见的四舍五入方法及其代码示例:

1. 使用Math.round()方法

Math.round()方法可以将浮点数四舍五入到最接近的整数。如果你需要四舍五入到特定的小数位数,可以先将数字乘以10的n次方(n为你想要保留的小数位数),然后使用Math.round()进行四舍五入,最后再除以10的n次方得到结果。

public class RoundExample {  
    public static void main(String[] args) {  
        double num = 3.14159;  
        int decimalPlaces = 2; // 保留两位小数  
        double roundedNum = Math.round(num * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);  
        System.out.println(roundedNum); // 输出 3.14  
    }  
}

2. 使用BigDecimal类

BigDecimal类提供了更精确的浮点数运算能力,包括四舍五入。它的setScale()方法可以用来设置小数点后的位数,并可以通过第二个参数指定舍入模式,例如BigDecimal.ROUND_HALF_UP代表四舍五入。

import java.math.BigDecimal;  
import java.math.RoundingMode;  
  
public class BigDecimalRoundExample {  
    public static void main(String[] args) {  
        BigDecimal num = new BigDecimal("3.14159");  
        int decimalPlaces = 2; // 保留两位小数  
        BigDecimal roundedNum = num.setScale(decimalPlaces, RoundingMode.HALF_UP);  
        System.out.println(roundedNum); // 输出 3.14  
    }  
}

3. 使用String.format()方法

虽然String.format()方法主要用于格式化字符串,但它也可以用于四舍五入浮点数到指定的小数位数。该方法不直接改变数字,而是将其格式化为包含指定小数位数的字符串。

public class StringFormatExample {  
    public static void main(String[] args) {  
        double num = 3.14159;  
        String roundedNumStr = String.format("%.2f", num);  
        double roundedNum = Double.parseDouble(roundedNumStr); // 如果需要再次作为double类型使用  
        System.out.println(roundedNum); // 输出 3.14  
    }  
}

注意,使用String.format()方法时,结果是一个字符串,如果你需要将其作为浮点数进行进一步操作,可以使用Double.parseDouble()将其转换回double类型。

4. 使用DecimalFormat类

DecimalFormatNumberFormat的一个具体子类,用于格式化十进制数。它允许你为数字、整数和小数指定模式。

import java.text.DecimalFormat;  
  
public class DecimalFormatExample {  
    public static void main(String[] args) {  
        double num = 3.14159;  
        DecimalFormat df = new DecimalFormat("#.##"); // 保留两位小数  
        String roundedNumStr = df.format(num);  
        double roundedNum = Double.parseDouble(roundedNumStr); // 如果需要再次作为double类型使用  
        System.out.println(roundedNum); // 输出 3.14  
    }  
}

String.format()类似,DecimalFormat的结果也是一个字符串,可以通过Double.parseDouble()转换回double类型。

以上就是在Java中进行四舍五入到特定小数位数的几种常见方法。每种方法都有其适用场景,可以根据具体需求选择使用。

总结

到此这篇关于Java中常见的几种四舍五入方法的文章就介绍到这了,更多相关Java四舍五入方法内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

您可能感兴趣的文章:
  • java 四舍五入使java保留2位小数示例讲解
  • java中DecimalFormat四舍五入用法详解
  • java中的取整与四舍五入方法实例
  • 详解java的四舍五入与保留位示例
  • Java取整与四舍五入
  • java 四舍五入保留小数的实现方法
  • Java四舍五入时保留指定小数位数的五种方式
  • Java DecimalFormat 保留小数位及四舍五入的陷阱介绍
  • 关于java四舍五入方法的基础学习
相关栏目:

用户点评