From f482ed3b7cca2cb5d251d7f63f600210b19fcb4f Mon Sep 17 00:00:00 2001 From: Chris Malley Date: Fri, 19 Jun 2015 11:14:49 -0600 Subject: [PATCH] #35 change Util.toFixed to use IEEE 754 "Round half away from zero" algorithm --- js/Util.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/js/Util.js b/js/Util.js index 269edb3..047922e 100644 --- a/js/Util.js +++ b/js/Util.js @@ -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 ); },