feat:增加数字缩写转换

This commit is contained in:
totalo 2021-02-19 17:35:36 +08:00
parent 9b6f7f2d14
commit ed520134ee
2 changed files with 157 additions and 108 deletions

View File

@ -2,6 +2,8 @@ package cn.hutool.core.convert;
import cn.hutool.core.util.StrUtil;
import java.text.DecimalFormat;
/**
* 将浮点数类型的number转换成英语的表达方式 <br>
* 参考博客http://blog.csdn.net/eric_sunah/article/details/8713226
@ -19,6 +21,8 @@ public class NumberWordFormatter {
"SEVENTY", "EIGHTY", "NINETY"};
private static final String[] NUMBER_MORE = new String[]{"", "THOUSAND", "MILLION", "BILLION"};
private static final String[] NUMBER_SUFFIX = new String[]{"k", "w", "", "m", "", "", "b", "", "", "t", "", "", "p", "", "", "e"};
/**
* 将阿拉伯数字转为英文表达式
*
@ -33,6 +37,42 @@ public class NumberWordFormatter {
}
}
/**
* 将阿拉伯数字转化为简介计数单位例如 2100 => 2.1k
* 范围默认只到w
* @param value
* @return
*/
public static String formatValue(long value) {
return formatValue(value, true);
}
/**
* 将阿拉伯数字转化为简介计数单位例如 2100 => 2.1k
* @param value 对应数字的值
* @param isTwo 控制是否为kw
* @return
*/
public static String formatValue(long value, boolean isTwo) {
if (value < 1000) {
return String.valueOf(value);
}
int index = -1;
double res = value * 1.0d;
while (res > 10 && (!isTwo || index < 1)) {
if (res > 1000) {
res = res / 1000;
index++;
}
if (res > 10) {
res = res / 10;
index++;
}
}
DecimalFormat decimalFormat = new DecimalFormat("#.##");
return String.format("%s%s", decimalFormat.format(res), NUMBER_SUFFIX[index]);
}
/**
* 将阿拉伯数字转为英文表达式
*

View File

@ -12,5 +12,14 @@ public class NumberWordFormatTest {
String format2 = NumberWordFormatter.format("2100.00");
Assert.assertEquals("TWO THOUSAND ONE HUNDRED AND CENTS ONLY", format2);
String format3 = NumberWordFormatter.formatValue(4384324, false);
Assert.assertEquals("4.38m", format3);
String format4 = NumberWordFormatter.formatValue(4384324);
Assert.assertEquals("438.43w", format4);
String format5 = NumberWordFormatter.formatValue(438);
Assert.assertEquals("438", format5);
}
}