十进制小数转二进制小数_Java十进制舍入到四舍五入,浮点到“ n”个小数点和不同的舍入模式

十进制小数转二进制小数

Sometimes while working with double and floats, we need to round them to specific decimal points for calculation. For example, stores round final price to 2 decimal places with half-up rounding mode.

有时在使用doublefloat时 ,我们需要将它们四舍五入到特定的小数点以进行计算。 例如,商店使用上半舍入模式将最终价格舍入到小数点后两位。

Prior to Java 5, DecimalFormat class was used for rounding purpose but working with it was not in line with numbers and it doesn’t provide many options. So Java 5 introduced RoundingMode enum and BigDecimal class was enhanced to use RoundingMode to get almost any type of rounding you want.

在Java 5之前, DecimalFormat类用于四舍五入,但使用它与数字不一致,并且它不提供很多选项。 因此,Java 5引入了RoundingMode 枚举,并且BigDecimal类得到了增强,可以使用RoundingMode来获取所需的几乎所有类型的舍入。

Using BigDecimal with RoundingMode feels like you are working with decimals and it’s very easy to use. Here is a sample program showing it’s usage.

将BigDecimal与RoundingMode一起使用时,感觉就像您正在使用小数,并且非常易于使用。 这是显示其用法的示例程序。

package com.journaldev.misc;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class RoundingExample {

    public static void main(String[] args) {
        double l = 100.34567890;
        
        //similar like RegEx but don't have much options
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.println(df.format(l));
        
        //2 decimal places rounding with half up rounding mode
        System.out.println(BigDecimal.valueOf(l).setScale(2, RoundingMode.HALF_UP));
        
        //3 decimal places rounding with ceiling rounding mode
        System.out.println(BigDecimal.valueOf(l).setScale(3, RoundingMode.CEILING));
        System.out.println(BigDecimal.valueOf(l).setScale(0, RoundingMode.CEILING));
        
        //integer rounding with floor rounding mode
        System.out.println(BigDecimal.valueOf(l).setScale(0, RoundingMode.FLOOR));
    }

}

翻译自: https://www.journaldev.com/1362/java-decimal-rounding-round-double-float-to-decimal-points-and-different-rounding-mode

十进制小数转二进制小数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值