JS代码:
function c(str) { console.log(str); }function format_price($money){ var cny = parseFloat($money).toFixed(2); var _num = ["0","壹","贰","叁","肆","伍","陆","柒","捌","玖"]; var _unit = ["圆","整","角","分"]; var _unit2 = ["","拾","佰","仟"]; var _unit3 = ["","万","亿","万","亿"]; var _cny = cny.split("."); if(_cny[0] == 0 && _cny[1] == 0){ return "零" + _unit[0] + _unit[1]; } var res = ""; var i = _cny[0].length - 1; for(var j = 0; i >= 0;j++){ str = ""; for(var k = 0; k < 4 && i >= 0; k++) { $_unit = _cny[0][i] > 0 ? _unit2[k] : ""; //倒找,找出各种单位 str = _num [ _cny[0] [i]] + $_unit + str; i--; } str = str.replace(/(0*$)/g, "");//替换最后一个0 str = str.replace ( /0+/g, "零" ); // 替换多个连续的0 $_unit2 = str != "" ? _unit3 [j] : ""; res = str+ $_unit2 + res; } str = ""; if (parseInt( _cny[1] ) > 0) { _a = _cny[1][0]; _b = _cny[1][1]; $_unit = _b > 0 ? _unit [3] : ""; str = _num [_b] + $_unit; $_unit = _a > 0 ? _unit [2] : ""; str = _num [_a] + $_unit + str; str = str.replace(/(0*$)/g, "");//替换最后一个0 str = str.replace(/0+/g, "零"); // 替换多个连续的0 } str = str.length == 0 ? "" + _unit [0] + _unit [1] : "" + _unit [0] + str; c("0>>"+str); res += str; c(res); return res; }
PHP代码:
/**
* 把数值格式化成大写人民币
*
* @param nember $money
* @return string|mixed
*/
function format_price_cny($money) {
$cny = number_format ( $money, 2, “.”, “” );$num = array (
“0”,
“壹”,
“贰”,
“叁”,
“肆”,
“伍”,
“陆”,
“柒”,
“捌”,
“玖”
);
$unit = array (
“圆”,
“整”,
“角”,
“分”
);
$unit2 = array (
“”,
“拾”,
“佰”,
“仟”
);$unit3 = array (
“”,
“万”,
“亿”,
“万”,
“亿”
);list ( $ns1, $ns2 ) = explode ( “.”, $cny, 2 );
if (intval ( $ns1 ) == 0 && intval ( $ns2 ) == 0) {
return “零” . $unit [0] . $unit [1];
}$res = “”;
for($i = strlen ( $ns1 ) – 1, $k = 0; $i >= 0; $k ++) {
$str = “”;for($j = 0; $j < 4 && $i >= 0; $j ++) {
$_unit = $ns1 {$i} > 0 ? $unit2 [$j] : “”; // 倒找,找出各种单位
$str = $num [$ns1 {$i}] . $_unit . $str;$i –;
}$str = rtrim ( $str, ‘0’ ); // 去掉末尾的0
$str = preg_replace ( “/0+/”, “零”, $str ); // 替换多个连续的0$_unit2 = $str != “” ? $unit3 [$k] : “”;
$res = $str . $_unit2 . $res;
}$str = “”;
if (intval ( $ns2 ) > 0) {$_a = $ns2 {0};
$_b = $ns2 {1};$_unit = $_b > 0 ? $unit [3] : “”;
$str = $num [$_b] . $_unit;$_unit = $_a > 0 ? $unit [2] : “”;
$str = $num [$_a] . $_unit . $str;$str = rtrim ( $str, ‘0’ ); // 去掉末尾的0
$str = preg_replace ( “/0+/”, “零”, $str ); // 替换多个连续的0
}
$str = strlen ( $str ) == 0 ? $unit [0] . $unit [1] : $unit [0] . $str;$res .= $str;
return $res;
}