如何将数值转换为印度货币简写格式(附Java实现代码)
印度货币体系数值简写转换实现
需求概述
需将数值转换为印度货币体系下的简写格式,具体转换示例如下:
- 6500 → 6.5K
- 50000 → 50K
- 99900 → 99.9K
- 100000 → 1Lakh
- 150000 → 1.5Lakh
- 1000000 → 10Lakh
- 1450000 → 14.5Lakh
- 50000000 → 5Cr
- 55000000 → 5.5Cr
验证可行的Java实现代码
private static String indianCurrencyShortForm(double amount) { double finalVal; String postfix; if (amount < 1000) { return String.valueOf(amount); } else if (amount < 100000) { finalVal = amount / 1000; postfix = "K"; } else if (amount < 10000000) { finalVal = amount / 100000; postfix = "Lakh"; } else { finalVal = amount / 10000000; postfix = "Cr"; } boolean isRound = (finalVal * 10) % 10 == 0; if (isRound){ return ((int) finalVal) + postfix; } else { /* 不用String.format("%.1f", finalVal)的原因:当输入99999时,会得到100.0K,不符合预期格式 * 因此拆分字符串处理小数部分,只保留非零的一位小数 */ String[] split = String.valueOf(finalVal).split("\\."); char fractionVal = split[1].charAt(0); return (split[0] + (fractionVal != '0' ? ("." + fractionVal) : "")) + postfix; } }
代码逻辑说明
- 数值区间判断:
- 小于1000:直接返回原数值
- 1000~100000:除以1000,后缀用
K - 100000~10000000:除以100000,后缀用
Lakh - 大于等于10000000:除以10000000,后缀用
Cr
- 小数格式处理:
- 判断转换后数值是否为整数,若是则直接取整拼接后缀
- 若含小数,拆分字符串仅保留第一位非零小数,避免出现
100.0K这类多余零的格式
内容的提问来源于stack exchange,提问作者Abhi Plx
相关产品推荐
相关产品推荐

