Last active
June 25, 2019 03:06
-
-
Save john-yuan/29d4ced19c417018d78da006edc0d0f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 格式化价格数字 | |
* | |
* @example | |
* // 123,456.00 | |
* formatPrice(123456); | |
* | |
* @param {number} price 价格数字 | |
* @param {string} [separator] 可选的分隔符号,默认为英文逗号 `,`。 | |
* @returns {string} 返回格式化后的价格字符串。 | |
*/ | |
function formatPrice(price, separator) { | |
var num = price; | |
var sep = separator; | |
var array = []; | |
var numbers; | |
var integer; | |
var decimal; | |
var sign; | |
if (typeof num !== 'number') { | |
num = parseFloat(num); | |
} | |
if (typeof sep !== 'string') { | |
sep = ','; | |
} | |
if (isNaN(num)) { | |
num = 0; | |
} | |
if (num < 0) { | |
sign = '-'; | |
num = -num; | |
} else { | |
sign = ''; | |
} | |
num = num.toFixed(2); | |
numbers = num.split('.'); | |
integer = numbers[0] || ''; | |
decimal = numbers[1] || '00'; | |
while (integer.length) { | |
if (integer.length > 3) { | |
array.unshift(integer.substr(-3)); | |
integer = integer.substr(0, integer.length - 3); | |
} else { | |
array.unshift(integer); | |
integer = ''; | |
} | |
} | |
return sign + array.join(sep) + '.' + decimal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment