Last active
May 2, 2018 07:34
-
-
Save guy-a/3390305 to your computer and use it in GitHub Desktop.
To Fix Javascript toFixed
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
/* https://blog.guya.net/2012/08/18/to-fix-javascript-tofixed/ | |
https://stackoverflow.com/a/11818658/275333 */ | |
function toFixed(num, fixed) { | |
var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?'); | |
return num.toString().match(re)[0]; | |
} |
Is this wrong too? http://www.jacklmoore.com/notes/rounding-in-javascript/
@guy-a the solution you provide simply truncates the result, not adding eventually necessary zeroes, so it can't be used as a replacement of toFixed. Plus, docs says that "The number is rounded if necessary". See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
So, your function should be called "truncateTo" or similar, and not "toFixed".
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are wrong giorgiobeggiora, the link you gave is missing the point.
The point is that there should be no rounding at all.
Check the updated gist for the solution.
And the discussion on StackOverflow
https://stackoverflow.com/a/11818658/275333