Created
December 21, 2012 11:33
-
-
Save bakso/4352283 to your computer and use it in GitHub Desktop.
前端计算价格区间时候的要用到的特定方法:舍弃后一位和增大前一位(一种自定义的toFixed方式)
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
/** | |
* 向下toFixed | |
* 例如: toFixedDown(0.407) == 0.40 | |
* @param {Number} num 数值 | |
* @param {Number} decimal 保留小数点后几位 | |
* @return {Number} | |
*/ | |
function toFixedDown(num, decimal){ | |
var decimal = decimal || 2, | |
nstr = parseFloat(num)+'', | |
dpos = nstr.indexOf('.'); | |
return nstr.slice(0, dpos + decimal + 1) * 1; | |
} | |
/** | |
* 向上toFixed | |
* 例如: toFixedUp(0.4001, 2) == 0.41 | |
* @param {Number} num 数值 | |
* @param {Number} decimal 保留小数点后几位 | |
* @return {Number} | |
*/ | |
function toFixedUp(num, decimal){ | |
var decimal = decimal || 2, | |
_num = toFixedDown(num, decimal); | |
return num > _num ? (_num + Math.pow(0.1, decimal)).toFixed(decimal) : _num | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
toFixedUp 返回的是string类型,toFixedDown返回的是0.4,未补0。补0啥的,是不是可以用位运算符 =。=