本文主要是介绍将数字翻译成英文,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class Demo { /* * Jessi初学英语,为了快速读出一串数字,编写程序将数字转换成英文: * 如22: twenty two ,123:one hundred and twenty three。 * * 注意事项: * 1、数字为正整数,长度不超过十位,不考虑小数,转化结果为英文小写; * 2、输出格式为twenty two; * 3、非法数据请返回“error”; * 4、关键词提示:and, billion,million, thousand, hundred 。 * * 输入参数: * long num 输入的数字,如1234 * 返回值: * 正常情况下返回数字对应的英文,如one thousand two hundred and thirty four */ public static String parse(long num) { if(num >= 10000000000L || num < 0L){ return "error"; } StringBuffer sb = new StringBuffer(); if(num >= 1000000000L){ sb.append(subParse1(num / 1000000000L)); sb.append(" billion"); if(num / 1000000000L > 1){ sb.append("s"); } num = num % 1000000000L; } if(num >= 1000000L){ if(!sb.toString().equals("")){ sb.append(" "); } sb.append(subParse1(num / 1000000L)); sb.append(" million"); if(num / 1000000L > 1){ sb.append("s"); } num = num % 1000000L; } if(num >= 1000L){ if(!sb.toString().equals("")){ sb.append(" "); } sb.append(subParse1(num / 1000L)); sb.append(" thousand"); if(num / 1000L > 1){ sb.append("s"); } num = num % 1000L; } if(num > 0){ if(!sb.toString().equals("")){ sb.append(" "); } sb.append(subParse1(num)); }else{ if(sb.toString().equals("")){ sb.append("zero"); } } return sb.toString().trim(); } /** * 个数最多只有三位的读法 * @param num * @return */ public static String subParse1(long num){ Integer i = (int) num; String[] str0to19 = new String[]{ "zero","one","two","three","four","five", "six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen", "sixteen","seventeen","eighteen","nineteen" }; String[] str20to90 = new String[]{ "twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety" }; StringBuffer result = new StringBuffer(); if(i >= 100){ result.append(str0to19[i/100]); result.append(" hundred"); if(i / 100 > 1){ result.append("s"); } i = i % 100; } if(i >= 20){ if(!result.toString().equals("")){ result.append(" and "); } result.append(str20to90[i/10 - 2]); if(i % 10 != 0){ result.append(" " + str0to19[i % 10]); } }else if(i > 0){ if(!result.toString().equals("")){ result.append(" and "); } result.append(str0to19[i]); } return result.toString().trim(); }}
这篇关于将数字翻译成英文的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!