java 货币格式 转换_JAVA——如何用货币格式将字符串转换成大十进制

数字格式始终是特定于区域设置的。因此,需要定义一个区域设置。

以下方法可用于格式化:

BigDecimal money = new BigDecimal("1234567");

DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.GERMAN);

symbols.setDecimalSeparator(',');

symbols.setGroupingSeparator('.');

// https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

DecimalFormat format = new DecimalFormat("###,###.00");

format.setDecimalFormatSymbols(symbols);

System.out.println(format.format(money));

但是,这不符合将任何给定数字解析为具有2位数字的十进制数的要求。在这里,我个人会用100除法,或者在给定的字符串中插入一个小数分隔符。

BigDecimal money = new BigDecimal("1234567").divide(new BigDecimal("100"));

插入定义的小数分隔符的工作方式如下:

private static String prepare(String input) {

if (input.length() == 2) {

return ","+input;

}

if (input.length() == 1) {

return ",0"+input;

}

String integerPart = input.substring(0, input.length()-2);

String fraction = input.substring(input.length()-2);

return integerPart+","+fraction;

}

使用新的decimalformat和

prepare()

方法默认情况下,将字符串解析为2位小数。

String input = "1234567";

String prepared = prepare(input);

DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.GERMAN);

symbols.setDecimalSeparator(',');

symbols.setGroupingSeparator('.');

DecimalFormat format = new DecimalFormat("###,###.00");

format.setDecimalFormatSymbols(symbols);

format.setParseBigDecimal(true);

BigDecimal bigDecimal = (BigDecimal)format.parse(prepared);

String n = format.format(bigDecimal);

System.out.println(n);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值