十进制小数转二进制小数
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.
有时在使用double和float时 ,我们需要将它们四舍五入到特定的小数点以进行计算。 例如,商店使用上半舍入模式将最终价格舍入到小数点后两位。
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));
}
}
十进制小数转二进制小数