Commit | Line | Data |
---|---|---|
ad35859f TD |
1 | /** |
2 | * Provides helper functions for Number handling. | |
3 | * | |
4 | * @author Tim Duesterhus | |
5 | * @copyright 2001-2015 WoltLab GmbH | |
6 | * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> | |
7 | * @module WoltLab/WCF/NumberUtil | |
8 | */ | |
9 | define([], function() { | |
10 | "use strict"; | |
11 | ||
12 | /** | |
13 | * @constructor | |
14 | */ | |
15 | function NumberUtil() { }; | |
16 | NumberUtil.prototype = { | |
17 | /** | |
18 | * Decimal adjustment of a number. | |
19 | * | |
20 | * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round | |
21 | * @param {Number} value The number. | |
22 | * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). | |
23 | * @returns {Number} The adjusted value. | |
24 | */ | |
25 | round: function (value, exp) { | |
26 | // If the exp is undefined or zero... | |
27 | if (typeof exp === 'undefined' || +exp === 0) { | |
28 | return Math.round(value); | |
29 | } | |
30 | value = +value; | |
31 | exp = +exp; | |
32 | ||
33 | // If the value is not a number or the exp is not an integer... | |
34 | if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { | |
35 | return NaN; | |
36 | } | |
37 | ||
38 | // Shift | |
39 | value = value.toString().split('e'); | |
40 | value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); | |
41 | ||
42 | // Shift back | |
43 | value = value.toString().split('e'); | |
44 | return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); | |
45 | } | |
46 | }; | |
47 | ||
48 | return new NumberUtil(); | |
49 | }); |