Skip to content

Commit

Permalink
#35 add Util.roundSymmetic, use it in Util.toFixed
Browse files Browse the repository at this point in the history
  • Loading branch information
pixelzoom committed Jun 19, 2015
1 parent f482ed3 commit 96a8851
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions js/Util.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,23 +252,34 @@ define( function( require ) {
return ( b2 - b1 ) / ( a2 - a1 ) * ( a3 - a1 ) + b1;
},

/**
* Rounds using "Round half away from zero" algorithm. See dot#35.
*
* JavaScript's Math.round is not symmetric for positive and negative numbers, it uses IEEE 754 "Round half up".
* See https://en.wikipedia.org/wiki/Rounding#Round_half_up.
* For sims, we want to treat positive and negative values symmetrically, which is IEEE 754 "Round half away from zero",
* See https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
*
* @param {number} value
* @returns {number}
*/
roundSymmetric: function( value ) {
return ( ( value < 0 ) ? -1 : 1 ) * Math.round( Math.abs( value ) );
},

/**
* 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).
* Rounding is symmetric for positive and negative values, see Util.roundSymmetric.
*
* @param {number} number
* @param {number} decimalPlaces
* @returns {string}
*/
toFixed: function( number, decimalPlaces ) {
var multiplier = Math.pow( 10, decimalPlaces );
var value = Math.round( Math.abs( number ) * multiplier ) / multiplier;
if ( number < 0 ) { value *= -1; }
var value = Util.roundSymmetric( number * multiplier ) / multiplier;
return value.toFixed( decimalPlaces );
},

Expand Down

0 comments on commit 96a8851

Please sign in to comment.