META-INF.resources.bower_components.globalize.src.util.number.round.js Maven / Gradle / Ivy
define([
"./truncate"
], function (numberTruncate) {
/**
* round( method )
*
* @method [String] with either "round", "ceil", "floor", or "truncate".
*
* Return function( value, incrementOrExp ):
*
* @value [Number] eg. 123.45.
*
* @incrementOrExp [Number] optional, eg. 0.1; or
* [Object] Either { increment: } or { exponent: }
*
* Return the rounded number, eg:
* - round( "round" )( 123.45 ): 123;
* - round( "ceil" )( 123.45 ): 124;
* - round( "floor" )( 123.45 ): 123;
* - round( "truncate" )( 123.45 ): 123;
* - round( "round" )( 123.45, 0.1 ): 123.5;
* - round( "round" )( 123.45, 10 ): 120;
*
* Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
* Ref: #376
*/
return function (method) {
method = method || "round";
method = method === "truncate" ? numberTruncate : Math[method];
return function (value, incrementOrExp) {
var exp, increment;
value = +value;
// If the value is not a number, return NaN.
if (isNaN(value)) {
return NaN;
}
// Exponent given.
if (typeof incrementOrExp === "object" && incrementOrExp.exponent) {
exp = +incrementOrExp.exponent;
increment = 1;
if (exp === 0) {
return method(value);
}
// If the exp is not an integer, return NaN.
if (!(typeof exp === "number" && exp % 1 === 0)) {
return NaN;
}
// Increment given.
} else {
increment = +incrementOrExp || 1;
if (increment === 1) {
return method(value);
}
// If the increment is not a number, return NaN.
if (isNaN(increment)) {
return NaN;
}
increment = increment.toExponential().split("e");
exp = +increment[1];
increment = +increment[0];
}
// Shift & Round
value = value.toString().split("e");
value[0] = +value[0] / increment;
value[1] = value[1] ? (+value[1] - exp) : -exp;
value = method(+(value[0] + "e" + value[1]));
// Shift back
value = value.toString().split("e");
value[0] = +value[0] * increment;
value[1] = value[1] ? (+value[1] + exp) : exp;
return +(value[0] + "e" + value[1]);
};
};
});
© 2015 - 2025 Weber Informatics LLC | Privacy Policy