Created
January 12, 2015 03:39
-
-
Save Lynn-cc/00c74aea1470d96b600e to your computer and use it in GitHub Desktop.
使数字保留一定小数位数,返回格式化数字的字符串
This file contains hidden or 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
var getFloat = function(number, len) { | |
var lessZero = (number < 0); | |
var arr; | |
var result; | |
function zeroTail(n) { | |
return (new Array(n + 1)).join('0'); | |
} | |
number = Math.abs(number); | |
len = (len > 1) ? parseInt(len, 10) : 1; | |
if (number === 0) { | |
result = '0.' + zeroTail(len); | |
} else { | |
// 分割成整数和小数两部分 | |
arr = (number + '').split('.'); | |
if (arr[1]) { | |
// 有小数 | |
if (arr[1].length > len) { | |
// 位数多了 | |
var intNum = Math.round(number * Math.pow(10, len)); | |
if (intNum > 0) { | |
// 至少有一位非0数 | |
result = getFloat(intNum / Math.pow(10, len), len); | |
} else { | |
// 四舍五入还是为0 | |
result = '0.' + zeroTail(len); | |
} | |
} else if (arr[1].length === len) { | |
// 位数正好 | |
result = number + ''; | |
} else { | |
// 位数不够,补齐 | |
result = number + zeroTail(len - arr[1].length); | |
} | |
} else { | |
// 没有小数 | |
result = number + '.' + (new Array(len + 1)).join('0'); | |
} | |
} | |
return (lessZero ? '-' : '') + result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment