Skip to content

Instantly share code, notes, and snippets.

@wteuber
Last active December 25, 2015 02:28
Show Gist options
  • Save wteuber/6902415 to your computer and use it in GitHub Desktop.
Save wteuber/6902415 to your computer and use it in GitHub Desktop.
/*jslint indent: 2 */
/* toFixed converts the input to a number and returns it rounded to 2 decimal places */
/* For a deeper insight on javascript numbers, read http://ecma-international.org/ecma-262/5.1/#sec-8.5 */
function toFixed(val) {
'use strict';
var floatError = 1000000, /* floating point errors less than (1/floatError) == 0.000001 will be corrected */
decRound = 100, /* the result is rounded to integer multiples of (1/decRound) == 0.01 */
n = parseFloat(val), /* convert input to floating point number */
sign = n < 0 ? '-' : '', /* sign of the given input */
intFrac, /* integer and fractional parts of a decimal number */
int, /* integer part of a decimal number */
frac, /* fractional part of a decimal number */
result, /* absolute result as floating point number */
roundCorrection = floatError / decRound; /* correct rounding offset between floatError and decRound */
result = Math.round(Math.abs(n) * floatError) / roundCorrection; /* result without floating point errors */
result = Math.round(result) / decRound; /* rounded result */
intFrac = result.toString().split('.');
int = intFrac[0];
frac = ((intFrac[1] || '00') + '0').substr(0, 2);
return sign + int + '.' + frac;
}
/*
toFixed() is implemented to deal with real world monetary calculations
toFixed() fixes float rounding errors smaller than 0.000001
toFixed() will fail when dealing with numbers greater than 1000000000
Don't use this implementation, if you want to deal with numbers
* greater than 1000000000 or
* less than 0.000001
*/
toFixed(0); /* "0.00" */
toFixed(1.5); /* "1.50" */
toFixed('3.5.1'); /* "3.50" */
toFixed(0.29 + 0.03); /* "0.32" */
toFixed(0.2 * 17.5 / 100); /* "0.04" */
toFixed(0.24499999999999995); /* "0.25" (assume floating point error) */
toFixed(-0.24499999999999995); /* "-0.25" (assume floating point error) */
toFixed(0.014994); /* "0.01" */
toFixed(0.014995); /* "0.01" */
toFixed(0.0149994); /* "0.01" */
toFixed(0.0149995); /* "0.02" */
toFixed(0.01499994); /* "0.02" (assume floating point error) */
toFixed(0.01499995); /* "0.02" (assume floating point error) */
toFixed(1000000000.014999); /* "1000000000.01" */
toFixed(10000000000.014999); /* "10000000000.02" (unavoidable error case, number too large) */
toFixed(1000000000.0149999); /* "1000000000.02" (assume floating point error) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment