首页 > 编程 > Java > 正文

java的四舍五入操作

2019-11-09 19:50:22
字体:
来源:转载
供稿:网友

java 中的四舍五入操作

本文主要总结在java中常用到的两种四舍五入方法。 方法一使用简单,但是缺点在于需要注意负数时的进位模式,并且只能将小数进位为long型整数。 方法二较为复杂,但是可以在开发后当工具使用。好处在于:保留指定位数小数并且正数和负数在进位时规则保持一致。

在java.lang.Math类中定义一个用于四舍五入操作的方法: publicstaticlonground(doublea),但是使用该方法需要注意一点:如果是负数进行四舍五入,其小数位的数值如果$/color{red}{小于等于5}不会进位,大于5才会进位。代码示例如下:import java.lang.Math;public class TestDemo{ public static void main(String [] args) { double a = 16.50; double b = 16.51; double c = -16.50; double d = -16.51; System.out.PRintln(Math.round(a)); System.out.println(Math.round(b)); System.out.println(Math.round(c)); System.out.println(Math.round(d)); }}

程序执行结果 17 17 -16 -17 通过程序执行结果,在使用round()方法进行四舍五入操作时,应注意都到这一点。 2. 使用BigDecimal类实现准确的四舍五入操作 BigDecimal类表示的是大小数操作类。要使用BigDecimal类完成准确的四舍五入运算,需要用到该类中的定义的如下常量和方法:

常量或方法 类型 描述
public static int ROUND_HALF_UP 常量 向上进位
public BigDecimal(double val) 构造函数 传递一个double型数据
public BigDecimal divvide(BigDecimal divisor, int scale, int roundingMode) 普通函数 除法操作,设置保留小数位数及进位模式

代码示例如下:

import java.math.BigDecimal;class MyMath{ /** * @param num 进行四舍五入操作的小数 * @param scale 指定保留小数位数 */ public static double round(double num, int scale) { BigDecimal big = new BigDecimal(num); BigDecimal result = big.divide(new BigDecimal(1), scale, BigDecimal.ROUND_HALF_UP); // 将BigDecimal型数据转换成double型数据并返回 return result.doubleValue(); }}public class TestDemo{ public static void main(String [] args) { double a = 16.5500; double b = 16.5510; double c = -16.5500; double d = -16.5510; System.out.println(MyMath.round(a, 1)); System.out.println(MyMath.round(b, 1)); System.out.println(MyMath.round(c, 1)); System.out.println(MyMath.round(d, 1)); }}

程序运行结果: 16.6 16.6 -16.6 -16.6

可以将MyMath类写成一个单独文件,并打包jar包,包所在路径加入CLASSPARH中,即可当成工具使用。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表