JS數字金額轉換為貨幣漢字形式
阿新 • • 發佈:2018-12-31
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is my JSP page. <br> <script type="text/javascript"> /** 數字金額大寫轉換(可以處理整數,小數,負數) */ function digit_uppercase(n) { var fraction = ['角', '分']; var digit = ['零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖']; var unit = [ ['元', '萬', '億'], ['', '拾', '佰', '仟'] ]; var head = n < 0? '欠': ''; n = Math.abs(n); var s = ''; for (var i = 0; i < fraction.length; i++) { s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, ''); } s = s || '整'; n = Math.floor(n); for (var i = 0; i < unit[0].length && n > 0; i++) { var p = ''; for (var j = 0; j < unit[1].length && n > 0; j++) { p = digit[n % 10] + unit[1][j] + p; n = Math.floor(n / 10); } s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s; } return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整'); } /** 整數測試資料 alert(digit_uppercase(0)); // 零元整 alert(digit_uppercase(123)); // 壹佰貳拾叄元整 alert(digit_uppercase(1000000)); // 壹佰萬元整 alert(digit_uppercase(100000001)); // 壹億零壹元整 alert(digit_uppercase(1000000000)); // 壹拾億元整 alert(digit_uppercase(1234567890)); // 壹拾貳億叄仟肆佰伍拾陸萬柒仟捌佰玖拾元整 alert(digit_uppercase(1001100101)); // 壹拾億零壹佰壹拾萬零壹佰零壹元整 alert(digit_uppercase(110101010)); // 壹億壹仟零壹拾萬壹仟零壹拾元整 */ /** 小數測試資料 alert(digit_uppercase(0.12)); // 壹角貳分 alert(digit_uppercase(123.34)); // 壹佰貳拾叄元叄角肆分 alert(digit_uppercase(1000000.56)); // 壹佰萬元伍角陸分 alert(digit_uppercase(100000001.78)); // 壹億零壹元柒角捌分 alert(digit_uppercase(1000000000.90)); // 壹拾億元玖角 alert(digit_uppercase(1234567890.03)); // 壹拾貳億叄仟肆佰伍拾陸萬柒仟捌佰玖拾元叄分 alert(digit_uppercase(1001100101.00)); // 壹拾億零壹佰壹拾萬零壹佰零壹元整 alert(digit_uppercase(110101010.10)); // 壹億壹仟零壹拾萬壹仟零壹拾元壹角 */ /** 負數(欠款)測試資料 alert(digit_uppercase(-0.12)); // 欠壹角貳分 alert(digit_uppercase(-123.34)); // 欠壹佰貳拾叄元叄角肆分 alert(digit_uppercase(-1000000.56)); // 欠壹佰萬元伍角陸分 alert(digit_uppercase(-100000001.78)); // 欠壹億零壹元柒角捌分 alert(digit_uppercase(-1000000000.90)); // 欠壹拾億元玖角 alert(digit_uppercase(-1234567890.03)); // 欠壹拾貳億叄仟肆佰伍拾陸萬柒仟捌佰玖拾元叄分 alert(digit_uppercase(-1001100101.00)); // 欠壹拾億零壹佰壹拾萬零壹佰零壹元整 alert(digit_uppercase(-110101010.10)); // 欠壹億壹仟零壹拾萬壹仟零壹拾元壹角 */ </script> </body> </html>