JS formats numerical amounts separated by commas and retains two decimal places_javascript skills
WBOY
Release: 2016-05-16 17:19:42
Original
1840 people have browsed it
For example: 12345 is formatted as 12,345.00 12345.6 is formatted as 12,345.60 12345.67 is formatted as 12,345.67 Leave only two decimal places. After I came back, I wrote a formatting function. You can control the number of decimal places and automatically round off. The code is as follows:
function fmoney(s, n) { n = n > 0 && n <= 20 ? n : 2; s = parseFloat((s "").replace(/[^d.-]/g, "")).toFixed (n) ""; var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1]; t = ""; for (i = 0; i < l.length; i ) { t = l[i] ((i 1) % 3 == 0 && (i 1) ! = l.length ? "," : ""); } return t.split("").reverse().join("") "." r; }
/* * formatMoney(s,type) * Function: Split the amount by commas in thousands * Parameter: s, the amount value that needs to be formatted. * Parameter : type, determine whether the formatted amount requires decimal places. * Return: Return the formatted numerical string. */ function formatMoney(s, type) { if ( /[^0-9.]/.test(s)) return "0"; if (s == null || s == "") return "0"; s = s.toString().replace(/^(d*)$/, "$1."); s = (s "00").replace(/(d*.dd)d*/ , "$1"); s = s.replace(".", ","); var re = /(d)(d{3},)/; while (re. test(s)) s = s.replace(re, "$1,$2"); s = s.replace(/,(dd)$/, ".$1"); if (type == 0) {// Without decimal places (default is with decimal places) var a = s.split("."); if (a[1] == "00") { s = a[0]; } } return s; } /* * General DateAdd(interval,number,date) Function: Implementation Date addition function of javascript. * Parameter: interval, string expression, indicating the time interval to be added. Parameter: number, numerical expression, indicating the number of time intervals to be added. Parameter: date, time Object. * Return: new time object. var now = new Date(); var newDate = DateAdd("day",5,now); * author:devinhua(starting from ○) update:2010 -5-5 20:35 */ function DateAdd(interval, number, date) { if (date == null) return ""; switch (interval) { case "day": date = new Date(date); date = date.valueOf(); date = number * 24 * 60 * 60 * 1000; date = new Date(date); return date; break; default: return ""; break; } }
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn