java 如何使用BigDecimal显示总是有2个小数点的数字?

0lvr5msh  于 2023-02-20  发布在  Java
关注(0)|答案(7)|浏览(188)

我正在使用 * BigDecimal * 来获取一些价格值。要求是这样的,无论我们从数据库中获取什么值,显示的值都应该有2个小数点。
例如:
获取的值为1-应显示为1.00
获取的值为1.7823-应显示为1.78
我正在使用setScale(2, BigDecimal.ROUND_HALF_UP),但仍然有一些地方,如果数据库中的数据是整数,那么显示的也是一样的!!
我的意思是,如果数据库中的值为0,则仅显示为0。我希望显示为0.00
谢谢

gijlo24d

gijlo24d1#

BigDecimal是不可变的,对其进行的任何操作(包括setScale(2,BigDecimal.ROUND_HALF_UP))都会生成一个新的BigDecimal。正确的代码应为

BigDecimal bd = new BigDecimal(1);
bd.setScale(2, BigDecimal.ROUND_HALF_UP); // this does change bd
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(bd);

输出

1.00

注意--由于Java 9 BigDecimal.ROUND_HALF_UP已被弃用,您现在应该使用RoundingMode.ROUND_HALF_UP

r8xiu3jd

r8xiu3jd2#

您可以使用上舍入格式

BigDecimal bd = new BigDecimal(2.22222);
System.out.println(bd.setScale(2,BigDecimal.ROUND_UP));

希望这对你有帮助。

cngwdvgl

cngwdvgl3#

要在JAVA中格式化数字,可以用途:

System.out.printf("%1$.2f", d);

其中d是变量或数字

DecimalFormat f = new DecimalFormat("##.00");  // this will helps you to always keeps in two decimal places
 System.out.println(f.format(d));
qni6mghb

qni6mghb4#

您需要使用类似NumberFormat的内容,并使用与format对应的语言环境

NumberFormat.getCurrencyInstance().format(bigDecimal);
4ktjp1zp

4ktjp1zp5#

bigDecimal.setScale就可以了。

nkkqxpd9

nkkqxpd96#

下面的代码可能会有所帮助。

protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
    final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    numberFormat.setGroupingUsed(true);
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    return numberFormat.format(input);
}
fdbelqdn

fdbelqdn7#

您可以按以下方式使用自定义注解:自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FormatBigDecimal {
    String format() default "0.00";
}

然后可以在字段上应用注解,并在构造函数中调用实现方法,如下所示:

public class TestClass {
   

    @FormatBigDecimal
    private BigDecimal myDecimal;
    public TestClass(BigDecimal myDecimal) throws ParseException, IllegalAccessException {
        this.myDecimal = myDecimal;
        formatBigDecimalFields();
    }

    public void setMyDecimal(BigDecimal myDecimal) {
        this.myDecimal = myDecimal;
    }

    public BigDecimal getMyDecimal() {
        return myDecimal;
    }
/**
In the above method, we are using reflection to get all the fields declared in the class. Then, we are iterating over all the fields and checking whether the @FormatBigDecimal annotation is present on the field. If it is present, we are making the field accessible and getting its value.

We are also getting the format string from the @FormatBigDecimal annotation and using it to create a DecimalFormat object with the desired format. Then, we are formatting the value of the field using the DecimalFormat object and storing the formatted value in a string.

Finally, we are parsing the formatted value back into a BigDecimal object and setting it as the value of the field.
**/
    public void formatBigDecimalFields() throws IllegalAccessException, ParseException {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(FormatBigDecimal.class)) {
                field.setAccessible(true);
                BigDecimal value = (BigDecimal) field.get(this);
                FormatBigDecimal formatAnnotation = field.getAnnotation(FormatBigDecimal.class);
                String formatString = formatAnnotation.format();
                NumberFormat format = NumberFormat.getNumberInstance(Locale.US);
                DecimalFormat decimalFormat = (DecimalFormat) format;
                decimalFormat.applyPattern(formatString);
                String formattedValue = decimalFormat.format(value);
                BigDecimal formattedDecimal = new BigDecimal(formattedValue);
                field.set(this, formattedDecimal);
            }
        }
    }

}

使用方法:

TestClass testClass = new TestClass(new BigDecimal("10000.899"));
        System.out.println(testClass.getMyDecimal());

将给予:10000.90

相关问题