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