作为中文的博客,有时候需要标记章节那当然得用中文了,但是可能格式并不统一,所以就需要将数字转化为对应的汉字,这个功能我们可以通过编程解决,经融行业的站点,可能也需要将数字转换为对应的大写汉字,下面就给大家分享两个转换的方法,一个是后端的 PHP,一个是前端的 JavaScript 方法。
先定义一些中文的数字数组和中文数字位数的称呼,然后遍历接收到的数字,替换阿拉伯数字为中文数字,最后返回这个字符串,源代码如下:
function ChNum($num, $mode=true) {
$char = array('零','一','二','三','四','五','六','七','八','九');
$dw = array('','十','百','千','','万','亿','兆');
$dec = '点';
$retval = '';
if($mode)
preg_match_all('/^0*(\d*)\.?(\d*)/',$num, $ar);
else
preg_match_all('/(\d*)\.?(\d*)/',$num, $ar);
if($ar[2][0] != '')
$retval = $dec . ChNum($ar[2][0],false); //如果有小数,先递归处理小数
if($ar[1][0] != '') {
$str = strrev($ar[1][0]);
for($i=0;$i<strlen($str);$i++) {
$out[$i] = $char[$str[$i]];
if($mode) {
$out[$i] .= $str[$i] != '0'? $dw[$i%4] : '';
if(@$str[$i]+@$str[$i-1] == 0)
$out[$i] = '';
if($i%4 == 0)
$out[$i] .= $dw[4+floor($i/4)];
}
}
$retval = join('',array_reverse($out)) . $retval;
}
return $retval;
}
这个 JavaScript 方法感觉算法更好,不过上面的 PHP 方法应该够用了。
function translateNumber(numberText) {
var CHINESE_NEGATIVE = "负";
var CHINESE_ZERO = "零";
var CHINESE_DIGITS = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
var CHINESE_UNITS = ["", "十", "百", "千"];
var CHINESE_GROUP_UNITS = ["", "万", "亿", "兆", "京", "垓", "杼", "穰", "溝", "澗", "正", "載", "極"];
if (numberText == "") {
return "";
}
numberText = numberText.replace(/^0+/g, "");
numberText = numberText.replace(/^-0+/g, "-");
if (numberText == "" || numberText == "-") {
return CHINESE_ZERO;
}
var result = "";
if (numberText[0] == "-") {
result += CHINESE_NEGATIVE;
numberText = numberText.substring(1);
}
var groupIsZero = true;
var needZero = false;
for (var i = 0; i < numberText.length; ++i) {
var position = numberText.length - 1 - i;
var digit = parseInt(numberText[i]);
var unit = position % CHINESE_UNITS.length;
var group = position / CHINESE_UNITS.length;
if (digit != 0) {
if (needZero) {
result += CHINESE_ZERO;
}
if (digit != 1 || unit != 1 || !groupIsZero || (group == 0 && needZero)) {
result += CHINESE_DIGITS[digit];
}
result += CHINESE_UNITS[unit];
}
groupIsZero = groupIsZero && (digit == 0);
if (unit == 0 && !groupIsZero) {
result += CHINESE_GROUP_UNITS[group];
}
needZero = (digit == 0 && (unit != 0 || groupIsZero));
if (unit == 0) {
groupIsZero = true;
}
}
return result;
}