Skip to content

Commit

Permalink
#35 change Util.toFixed to use IEEE 754 "Round half away from zero" a…
Browse files Browse the repository at this point in the history
…lgorithm
  • Loading branch information
pixelzoom committed Jun 19, 2015
1 parent 5c1c94c commit f482ed3
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion js/Util.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,13 +256,19 @@ define( function( require ) {
* A predictable implementation of toFixed.
* JavaScript's toFixed is notoriously buggy, behavior differs depending on browser,
* because the spec doesn't specify whether to round or floor.
*
* This is the IEEE 754 "Round half away from zero" algorithm, see
* https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
* It treats positive and negative values symmetrically, which is desirable for sims (see dot#35).
*
* @param {number} number
* @param {number} decimalPlaces
* @returns {string}
*/
toFixed: function( number, decimalPlaces ) {
var multiplier = Math.pow( 10, decimalPlaces );
var value = Math.round( number * multiplier ) / multiplier;
var value = Math.round( Math.abs( number ) * multiplier ) / multiplier;
if ( number < 0 ) { value *= -1; }
return value.toFixed( decimalPlaces );
},

Expand Down

0 comments on commit f482ed3

Please sign in to comment.