Created
June 22, 2016 08:44
-
-
Save mylxsw/c01bf9b1ee4aaaf3521803942776cb63 to your computer and use it in GitHub Desktop.
修正javascript浮点数四舍五入时,0.085->0.08的问题
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
/** | |
* 浮点数四舍五入 | |
* 修正0.085->0.08的问题 | |
*/ | |
Number.prototype.FloatToFixed = function(precision) { | |
"use strict"; | |
var number = this; | |
var str = Math.abs(number).toString(), | |
negative = number < 0, | |
lastNumber, mult; | |
var dot_pos = str.indexOf('.'); | |
if (dot_pos == -1) { | |
dot_pos = str.length; | |
} | |
str = str.substr(0, dot_pos + precision + 2); | |
var str_decimals = str.substr((str.indexOf('.') == -1 ? str.length : str.indexOf('.')) + 1); | |
if (str_decimals.length <= precision) { | |
return (str * (negative ? -1 : 1)).toFixed(precision); | |
} | |
lastNumber = str.charAt(str.length - 1); | |
str = str.substr(0, str.length - 1); | |
if (lastNumber >= 5) { | |
mult = Math.pow(10, str.length - str.indexOf('.') - 1); | |
str = (+str + 1 / mult).toFixed(precision); | |
} | |
return str * (negative ? -1 : 1); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment