Java四舍五入及保留小数点位数

关于java的四舍五入函数,精确到小数点后n位的方法。

1. 四舍五入函数
- Math.round(double a)
- Math.rint(double a)

long java.lang.Math.round(double a)
Returns the closest long to the argument, with ties rounding to positive infinity.

Special cases:

If the argument is NaN, the result is 0.
If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE.
If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.

Parameters:

    a a floating-point value to be rounded to a long.

Returns:

the value of the argument rounded to the nearest long value.
Math.round(2.50);
运行结果:3
Math.round(2.49);
运行结果:2

double java.lang.Math.rint(double a)

Returns the double value that is closest in value to the argument and is equal to a mathematical integer. If two double values that are mathematical integers are equally close, the result is the integer value that is even. Special cases:

If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
Parameters:

a a double value.

Returns:

the closest floating-point value to a that is equal to a mathematical integer.
Math.rint(2.51)
运行结果:3.0
Math.rint(2.50);//此处特殊,2.50也认为是舍,而比2.50大,才能入。
运行结果:2.0
----------

2. 舍函数Math.floor(2.8)

double java.lang.Math.floor(double a)

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. Special cases:

If the argument value is already equal to a mathematical integer, then the result is the same as the argument.
If the argument is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument.
Parameters:

a a value.

Returns:

the largest (closest to positive infinity) floating-point value that less than or equal to the argument and is equal to a mathematical integer.
Math.floor(2.8)
运行结果:2.0
Math.floor(2.3)
运行结果:2.0

3. 保留n位小数(精确到n位小数)

DecimalFormat d = new DecimalFormat("#.0");
System.out.println(d.format(2.5563));
运行结果:2.6
"#.0"表示保留一位小数
"#.00"表示保留两位小数
"#.000"表示保留三位小数
"#.0000"表示保留四位小数
...
...
以此类推
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子林Android

感谢老板,老板大气!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值