[英]BigDecimal with minimal 2 fraction digits
I saw Using BigDecimal to work with currencies but I have a little different problem. 我看到使用BigDecimal来处理货币,但我遇到了一些不同的问题。
I give object with BigDecimal parameters to PDF generation library and I can't use Formatter, only send objects. 我将带有BigDecimal参数的对象赋予PDF生成库,我不能使用Formatter,只能发送对象。 Is possible that default toString method always writes BigDecimal objects in format *.xx wg 134.40 ?
有可能默认的toString方法总是以格式* .xx wg 134.40写入BigDecimal对象吗?
I use setScale but it doesn't work for eg 134.300 because it writes 134.3 instead of 134.30 我使用setScale,但它不适用于例如134.300,因为它写入134.3而不是134.30
I assume the problem is that you have forgotten that BigDecimal is immutable and setScale doesn't alter the existing BigDecimal 我假设问题是您忘记了BigDecimal是不可变的并且setScale不会改变现有的BigDecimal
BigDecimal decimal = BigDecimal.valueOf(134.4);
BigDecimal decimal2 = decimal.setScale(2, RoundingMode.HALF_UP);
System.out.println(decimal2);
prints 版画
134.40
BTW to do the same thing with double
BTW用
double
做同样的事情
double d = 134.4;
System.out.printf("%.2f%n", d);
只需使用NumberFormat.getCurrencyInstance().format(n)
并将结果字符串传递给PDF生成库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.