Skip to content

Instantly share code, notes, and snippets.

@guy-a guy-a/toFixed.js
Last active May 2, 2018

Embed
What would you like to do?
To Fix Javascript toFixed
/* 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];
}
@anfaguerrero

This comment has been minimized.

Copy link

anfaguerrero commented Oct 28, 2014

var num = 12.99465;
with ur method throw = 12.99;
but must be 13.00.

@leojh

This comment has been minimized.

Copy link

leojh commented May 20, 2015

still broken.
toFixed(0.0450, 2) should be 0.05 but it returns 0.04

@giorgiobeggiora

This comment has been minimized.

Copy link

giorgiobeggiora commented Mar 13, 2018

@anfaguerrero you're wrong, 12.99 is correct because 4 is "less than 5".
@leojh you're right because 5 is "5 or more".

Might seem strange, but for my experience this works:

return Math.round((num * fixed).toFixed(2)) / fixed

(to be compliant with Number.toFixed, don't forget to add ending zeroes if necessary)

@giorgiobeggiora

This comment has been minimized.

@guy-a

This comment has been minimized.

Copy link
Owner Author

guy-a commented Mar 13, 2018

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

@giorgiobeggiora

This comment has been minimized.

Copy link

giorgiobeggiora commented Apr 30, 2018

@giorgiobeggiora

This comment has been minimized.

Copy link

giorgiobeggiora commented May 2, 2018

@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 can’t perform that action at this time.