【有用的算法】
1、阿拉伯数字转中文读法代码
Tips:仅整数,万万亿往上有bug;提供Java、Objective-C版本代码
测试数据:
110000:一十一万
100000200:一亿零二百
1000000323:一十亿零三百二十三
9999100323340034:九千九百九十九万亿一千零三亿二千三百三十四万零三十四
Java版
public String numberConvert(double n) {
if (n < 0) return "异常";
double number = n;
String[] numberChars = {"零","一","二","三","四","五","六","七","八","九"};
String[] units = {"", "十", "百", "千", "万","十", "百", "千", "亿", "十",
"百", "千", "万亿", "十", "百", "千", "万万亿", "十", "百", "千", "?"};
StringBuilder result = new StringBuilder();
int index = 0, isZero = 0; // index:数值单位下标递增,isZero:是否插入零,多个零只需读一个
while (number >= 1) {
if (index >= units.length) break;
int pop = (int) (number % 10);
number /= 10; // 从低位依次取出组成number的数字
String unit = units[index ++];
String readNum = numberChars[pop];
if (pop > 0) result.insert(0, unit);
else if (index % 4 == 1) result.insert(0, unit); // 避免零字后刚好跟单位
if (pop != 0) {
result.insert(0, readNum);
isZero = 0;
} else if (isZero == 0) { // readNum = 零且可插入零时,再避免零后刚好跟单位
if (index % 4 != 1) result.insert(0, readNum);
isZero = 1;
}
}
if (n == 0) result.append(numberChars[0]);
if (n / 10000 % 10000 < 1) { // 解决亿级数字万级全零多了个万字问题
int s = result.lastIndexOf("万");
if (s > 0 && s + 1 < result.length())
if (result.charAt(s + 1) != '零')
result.replace(s, s + 1, "零");
else result.delete(s, s + 1);
}
return result.toString();
}
Objective-C版
- (NSString *)numberConvert:(long)n {
if (n < 0) return @"异常";
long number = n;
NSArray *numberChars = @[@"零", @"一", @"二", @"三", @"四", @"五", @"六", @"七", @"八", @"九"];
NSArray *units = @[@"", @"十", @"百", @"千", @"万", @"十", @"百", @"千", @"亿", @"十", @"百",
@"千", @"万亿", @"十", @"百", @"千", @"万万亿", @"十", @"百", @"千", @"?"];
NSMutableString *result = [[NSMutableString alloc] initWithCapacity:0];
int index = 0, isZero = 0; // index:数值单位下标递增,isZero:是否插入零,多个零只需读一个
while (number > 0) {
if (index >= units.count) break;
int pop = (int)(number % 10);
number /= 10; // 从低位依次取出组成number的数字
NSString *unit = units[index ++];
NSString *readNum = numberChars[pop];
if (pop > 0) [result insertString:unit atIndex:0];
else if (index % 4 == 1) [result insertString:unit atIndex:0]; // 避免零字后刚好跟单位
if (pop != 0) {
[result insertString:readNum atIndex:0];
isZero = 0;
} else if (isZero == 0) { // readNum = 零且可插入零时,再避免零后刚好跟单位
if (index % 4 != 1) [result insertString:readNum atIndex:0];
isZero = 1;
}
}
if (n == 0) [result appendString:numberChars[0]];
if(n / 10000 % 10000 < 1) { // 解决亿级数字万级全零多了个万字问题
NSRange range = [result rangeOfString:units[4] options:NSBackwardsSearch];
// PS:此处还应判断越界
if ([[result substringWithRange:NSMakeRange(range.location + 1, 1)] isEqual:@"零"])
[result deleteCharactersInRange:range];
else [result replaceCharactersInRange:range withString:numberChars[0]];
}
return result;
}
有用 Mark一下
欢迎光临~[Wow]