1 | ;
|
2 |
|
3 | var objectUtils = require('./object');
|
4 |
|
5 | /**
|
6 | * @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue
|
7 | */
|
8 |
|
9 | /**
|
10 | * Test whether value is a number
|
11 | * @param {*} value
|
12 | * @return {boolean} isNumber
|
13 | */
|
14 | exports.isNumber = function (value) {
|
15 | return typeof value === 'number';
|
16 | };
|
17 |
|
18 | /**
|
19 | * Check if a number is integer
|
20 | * @param {number | boolean} value
|
21 | * @return {boolean} isInteger
|
22 | */
|
23 | exports.isInteger = function (value) {
|
24 | if (typeof value === 'boolean') {
|
25 | return true;
|
26 | }
|
27 |
|
28 | return isFinite(value) ? value === Math.round(value) : false;
|
29 | // Note: we use ==, not ===, as we can have Booleans as well
|
30 | };
|
31 |
|
32 | /**
|
33 | * Calculate the sign of a number
|
34 | * @param {number} x
|
35 | * @returns {*}
|
36 | */
|
37 | exports.sign = Math.sign || function (x) {
|
38 | if (x > 0) {
|
39 | return 1;
|
40 | } else if (x < 0) {
|
41 | return -1;
|
42 | } else {
|
43 | return 0;
|
44 | }
|
45 | };
|
46 |
|
47 | /**
|
48 | * Convert a number to a formatted string representation.
|
49 | *
|
50 | * Syntax:
|
51 | *
|
52 | * format(value)
|
53 | * format(value, options)
|
54 | * format(value, precision)
|
55 | * format(value, fn)
|
56 | *
|
57 | * Where:
|
58 | *
|
59 | * {number} value The value to be formatted
|
60 | * {Object} options An object with formatting options. Available options:
|
61 | * {string} notation
|
62 | * Number notation. Choose from:
|
63 | * 'fixed' Always use regular number notation.
|
64 | * For example '123.40' and '14000000'
|
65 | * 'exponential' Always use exponential notation.
|
66 | * For example '1.234e+2' and '1.4e+7'
|
67 | * 'engineering' Always use engineering notation.
|
68 | * For example '123.4e+0' and '14.0e+6'
|
69 | * 'auto' (default) Regular number notation for numbers
|
70 | * having an absolute value between
|
71 | * `lowerExp` and `upperExp` bounds, and
|
72 | * uses exponential notation elsewhere.
|
73 | * Lower bound is included, upper bound
|
74 | * is excluded.
|
75 | * For example '123.4' and '1.4e7'.
|
76 | * {number} precision A number between 0 and 16 to round
|
77 | * the digits of the number.
|
78 | * In case of notations 'exponential' and
|
79 | * 'auto', `precision` defines the total
|
80 | * number of significant digits returned.
|
81 | * In case of notation 'fixed',
|
82 | * `precision` defines the number of
|
83 | * significant digits after the decimal
|
84 | * point.
|
85 | * `precision` is undefined by default,
|
86 | * not rounding any digits.
|
87 | * {number} lowerExp Exponent determining the lower boundary
|
88 | * for formatting a value with an exponent
|
89 | * when `notation='auto`.
|
90 | * Default value is `-3`.
|
91 | * {number} upperExp Exponent determining the upper boundary
|
92 | * for formatting a value with an exponent
|
93 | * when `notation='auto`.
|
94 | * Default value is `5`.
|
95 | * {Function} fn A custom formatting function. Can be used to override the
|
96 | * built-in notations. Function `fn` is called with `value` as
|
97 | * parameter and must return a string. Is useful for example to
|
98 | * format all values inside a matrix in a particular way.
|
99 | *
|
100 | * Examples:
|
101 | *
|
102 | * format(6.4) // '6.4'
|
103 | * format(1240000) // '1.24e6'
|
104 | * format(1/3) // '0.3333333333333333'
|
105 | * format(1/3, 3) // '0.333'
|
106 | * format(21385, 2) // '21000'
|
107 | * format(12.071, {notation: 'fixed'}) // '12'
|
108 | * format(2.3, {notation: 'fixed', precision: 2}) // '2.30'
|
109 | * format(52.8, {notation: 'exponential'}) // '5.28e+1'
|
110 | * format(12345678, {notation: 'engineering'}) // '12.345678e+6'
|
111 | *
|
112 | * @param {number} value
|
113 | * @param {Object | Function | number} [options]
|
114 | * @return {string} str The formatted value
|
115 | */
|
116 | exports.format = function (value, options) {
|
117 | if (typeof options === 'function') {
|
118 | // handle format(value, fn)
|
119 | return options(value);
|
120 | }
|
121 |
|
122 | // handle special cases
|
123 | if (value === Infinity) {
|
124 | return 'Infinity';
|
125 | } else if (value === -Infinity) {
|
126 | return '-Infinity';
|
127 | } else if (isNaN(value)) {
|
128 | return 'NaN';
|
129 | }
|
130 |
|
131 | // default values for options
|
132 | var notation = 'auto';
|
133 | var precision = void 0;
|
134 |
|
135 | if (options) {
|
136 | // determine notation from options
|
137 | if (options.notation) {
|
138 | notation = options.notation;
|
139 | }
|
140 |
|
141 | // determine precision from options
|
142 | if (exports.isNumber(options)) {
|
143 | precision = options;
|
144 | } else if (options.precision) {
|
145 | precision = options.precision;
|
146 | }
|
147 | }
|
148 |
|
149 | // handle the various notations
|
150 | switch (notation) {
|
151 | case 'fixed':
|
152 | return exports.toFixed(value, precision);
|
153 |
|
154 | case 'exponential':
|
155 | return exports.toExponential(value, precision);
|
156 |
|
157 | case 'engineering':
|
158 | return exports.toEngineering(value, precision);
|
159 |
|
160 | case 'auto':
|
161 | // TODO: clean up some day. Deprecated since: 2018-01-24
|
162 | // @deprecated upper and lower are replaced with upperExp and lowerExp since v4.0.0
|
163 | if (options && options.exponential && (options.exponential.lower !== undefined || options.exponential.upper !== undefined)) {
|
164 | var fixedOptions = objectUtils.map(options, function (x) {
|
165 | return x;
|
166 | });
|
167 | fixedOptions.exponential = undefined;
|
168 | if (options.exponential.lower !== undefined) {
|
169 | fixedOptions.lowerExp = Math.round(Math.log(options.exponential.lower) / Math.LN10);
|
170 | }
|
171 | if (options.exponential.upper !== undefined) {
|
172 | fixedOptions.upperExp = Math.round(Math.log(options.exponential.upper) / Math.LN10);
|
173 | }
|
174 |
|
175 | console.warn('Deprecation warning: Formatting options exponential.lower and exponential.upper ' + '(minimum and maximum value) ' + 'are replaced with exponential.lowerExp and exponential.upperExp ' + '(minimum and maximum exponent) since version 4.0.0. ' + 'Replace ' + JSON.stringify(options) + ' with ' + JSON.stringify(fixedOptions));
|
176 |
|
177 | return exports.toPrecision(value, precision, fixedOptions);
|
178 | }
|
179 |
|
180 | return exports.toPrecision(value, precision, options && options)
|
181 |
|
182 | // remove trailing zeros after the decimal point
|
183 | .replace(/((\.\d*?)(0+))($|e)/, function () {
|
184 | var digits = arguments[2];
|
185 | var e = arguments[4];
|
186 | return digits !== '.' ? digits + e : e;
|
187 | });
|
188 |
|
189 | default:
|
190 | throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".');
|
191 | }
|
192 | };
|
193 |
|
194 | /**
|
195 | * Split a number into sign, coefficients, and exponent
|
196 | * @param {number | string} value
|
197 | * @return {SplitValue}
|
198 | * Returns an object containing sign, coefficients, and exponent
|
199 | */
|
200 | exports.splitNumber = function (value) {
|
201 | // parse the input value
|
202 | var match = String(value).toLowerCase().match(/^0*?(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);
|
203 | if (!match) {
|
204 | throw new SyntaxError('Invalid number ' + value);
|
205 | }
|
206 |
|
207 | var sign = match[1];
|
208 | var digits = match[2];
|
209 | var exponent = parseFloat(match[4] || '0');
|
210 |
|
211 | var dot = digits.indexOf('.');
|
212 | exponent += dot !== -1 ? dot - 1 : digits.length - 1;
|
213 |
|
214 | var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros)
|
215 | .replace(/^0*/, function (zeros) {
|
216 | // remove leading zeros, add their count to the exponent
|
217 | exponent -= zeros.length;
|
218 | return '';
|
219 | }).replace(/0*$/, '') // remove trailing zeros
|
220 | .split('').map(function (d) {
|
221 | return parseInt(d);
|
222 | });
|
223 |
|
224 | if (coefficients.length === 0) {
|
225 | coefficients.push(0);
|
226 | exponent++;
|
227 | }
|
228 |
|
229 | return {
|
230 | sign: sign,
|
231 | coefficients: coefficients,
|
232 | exponent: exponent
|
233 | };
|
234 | };
|
235 |
|
236 | /**
|
237 | * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
|
238 | * @param {number | string} value
|
239 | * @param {number} [precision=0] Optional number of decimals after the
|
240 | * decimal point. Zero by default.
|
241 | */
|
242 | exports.toEngineering = function (value, precision) {
|
243 | if (isNaN(value) || !isFinite(value)) {
|
244 | return String(value);
|
245 | }
|
246 |
|
247 | var rounded = exports.roundDigits(exports.splitNumber(value), precision);
|
248 |
|
249 | var e = rounded.exponent;
|
250 | var c = rounded.coefficients;
|
251 |
|
252 | // find nearest lower multiple of 3 for exponent
|
253 | var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
|
254 |
|
255 | // concatenate coefficients with necessary zeros
|
256 | var significandsDiff = e >= 0 ? e : Math.abs(newExp);
|
257 |
|
258 | // add zeros if necessary (for ex: 1e+8)
|
259 | if (c.length - 1 < significandsDiff) c = c.concat(zeros(significandsDiff - (c.length - 1)));
|
260 |
|
261 | // find difference in exponents
|
262 | var expDiff = Math.abs(e - newExp);
|
263 |
|
264 | var decimalIdx = 1;
|
265 |
|
266 | // push decimal index over by expDiff times
|
267 | while (--expDiff >= 0) {
|
268 | decimalIdx++;
|
269 | } // if all coefficient values are zero after the decimal point, don't add a decimal value.
|
270 | // otherwise concat with the rest of the coefficients
|
271 | var decimals = c.slice(decimalIdx).join('');
|
272 | var decimalVal = decimals.match(/[1-9]/) ? '.' + decimals : '';
|
273 |
|
274 | var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
|
275 | return rounded.sign + str;
|
276 | };
|
277 |
|
278 | /**
|
279 | * Format a number with fixed notation.
|
280 | * @param {number | string} value
|
281 | * @param {number} [precision=undefined] Optional number of decimals after the
|
282 | * decimal point. null by default.
|
283 | */
|
284 | exports.toFixed = function (value, precision) {
|
285 | if (isNaN(value) || !isFinite(value)) {
|
286 | return String(value);
|
287 | }
|
288 |
|
289 | var splitValue = exports.splitNumber(value);
|
290 | var rounded = typeof precision === 'number' ? exports.roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue;
|
291 | var c = rounded.coefficients;
|
292 | var p = rounded.exponent + 1; // exponent may have changed
|
293 |
|
294 | // append zeros if needed
|
295 | var pp = p + (precision || 0);
|
296 | if (c.length < pp) {
|
297 | c = c.concat(zeros(pp - c.length));
|
298 | }
|
299 |
|
300 | // prepend zeros if needed
|
301 | if (p < 0) {
|
302 | c = zeros(-p + 1).concat(c);
|
303 | p = 1;
|
304 | }
|
305 |
|
306 | // insert a dot if needed
|
307 | if (p < c.length) {
|
308 | c.splice(p, 0, p === 0 ? '0.' : '.');
|
309 | }
|
310 |
|
311 | return rounded.sign + c.join('');
|
312 | };
|
313 |
|
314 | /**
|
315 | * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
|
316 | * @param {number | string} value
|
317 | * @param {number} [precision] Number of digits in formatted output.
|
318 | * If not provided, the maximum available digits
|
319 | * is used.
|
320 | */
|
321 | exports.toExponential = function (value, precision) {
|
322 | if (isNaN(value) || !isFinite(value)) {
|
323 | return String(value);
|
324 | }
|
325 |
|
326 | // round if needed, else create a clone
|
327 | var split = exports.splitNumber(value);
|
328 | var rounded = precision ? exports.roundDigits(split, precision) : split;
|
329 | var c = rounded.coefficients;
|
330 | var e = rounded.exponent;
|
331 |
|
332 | // append zeros if needed
|
333 | if (c.length < precision) {
|
334 | c = c.concat(zeros(precision - c.length));
|
335 | }
|
336 |
|
337 | // format as `C.CCCe+EEE` or `C.CCCe-EEE`
|
338 | var first = c.shift();
|
339 | return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e;
|
340 | };
|
341 |
|
342 | /**
|
343 | * Format a number with a certain precision
|
344 | * @param {number | string} value
|
345 | * @param {number} [precision=undefined] Optional number of digits.
|
346 | * @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options]
|
347 | * By default:
|
348 | * lowerExp = -3 (incl)
|
349 | * upper = +5 (excl)
|
350 | * @return {string}
|
351 | */
|
352 | exports.toPrecision = function (value, precision, options) {
|
353 | if (isNaN(value) || !isFinite(value)) {
|
354 | return String(value);
|
355 | }
|
356 |
|
357 | // determine lower and upper bound for exponential notation.
|
358 | var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3;
|
359 | var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5;
|
360 |
|
361 | var split = exports.splitNumber(value);
|
362 | if (split.exponent < lowerExp || split.exponent >= upperExp) {
|
363 | // exponential notation
|
364 | return exports.toExponential(value, precision);
|
365 | } else {
|
366 | var rounded = precision ? exports.roundDigits(split, precision) : split;
|
367 | var c = rounded.coefficients;
|
368 | var e = rounded.exponent;
|
369 |
|
370 | // append trailing zeros
|
371 | if (c.length < precision) {
|
372 | c = c.concat(zeros(precision - c.length));
|
373 | }
|
374 |
|
375 | // append trailing zeros
|
376 | // TODO: simplify the next statement
|
377 | c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0)));
|
378 |
|
379 | // prepend zeros
|
380 | c = zeros(-e).concat(c);
|
381 |
|
382 | var dot = e > 0 ? e : 0;
|
383 | if (dot < c.length - 1) {
|
384 | c.splice(dot + 1, 0, '.');
|
385 | }
|
386 |
|
387 | return rounded.sign + c.join('');
|
388 | }
|
389 | };
|
390 |
|
391 | /**
|
392 | * Round the number of digits of a number *
|
393 | * @param {SplitValue} split A value split with .splitNumber(value)
|
394 | * @param {number} precision A positive integer
|
395 | * @return {SplitValue}
|
396 | * Returns an object containing sign, coefficients, and exponent
|
397 | * with rounded digits
|
398 | */
|
399 | exports.roundDigits = function (split, precision) {
|
400 | // create a clone
|
401 | var rounded = {
|
402 | sign: split.sign,
|
403 | coefficients: split.coefficients,
|
404 | exponent: split.exponent
|
405 | };
|
406 | var c = rounded.coefficients;
|
407 |
|
408 | // prepend zeros if needed
|
409 | while (precision <= 0) {
|
410 | c.unshift(0);
|
411 | rounded.exponent++;
|
412 | precision++;
|
413 | }
|
414 |
|
415 | if (c.length > precision) {
|
416 | var removed = c.splice(precision, c.length - precision);
|
417 |
|
418 | if (removed[0] >= 5) {
|
419 | var i = precision - 1;
|
420 | c[i]++;
|
421 | while (c[i] === 10) {
|
422 | c.pop();
|
423 | if (i === 0) {
|
424 | c.unshift(0);
|
425 | rounded.exponent++;
|
426 | i++;
|
427 | }
|
428 | i--;
|
429 | c[i]++;
|
430 | }
|
431 | }
|
432 | }
|
433 |
|
434 | return rounded;
|
435 | };
|
436 |
|
437 | /**
|
438 | * Create an array filled with zeros.
|
439 | * @param {number} length
|
440 | * @return {Array}
|
441 | */
|
442 | function zeros(length) {
|
443 | var arr = [];
|
444 | for (var i = 0; i < length; i++) {
|
445 | arr.push(0);
|
446 | }
|
447 | return arr;
|
448 | }
|
449 |
|
450 | /**
|
451 | * Count the number of significant digits of a number.
|
452 | *
|
453 | * For example:
|
454 | * 2.34 returns 3
|
455 | * 0.0034 returns 2
|
456 | * 120.5e+30 returns 4
|
457 | *
|
458 | * @param {number} value
|
459 | * @return {number} digits Number of significant digits
|
460 | */
|
461 | exports.digits = function (value) {
|
462 | return value.toExponential().replace(/e.*$/, '') // remove exponential notation
|
463 | .replace(/^0\.?0*|\./, '') // remove decimal point and leading zeros
|
464 | .length;
|
465 | };
|
466 |
|
467 | /**
|
468 | * Minimum number added to one that makes the result different than one
|
469 | */
|
470 | exports.DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16;
|
471 |
|
472 | /**
|
473 | * Compares two floating point numbers.
|
474 | * @param {number} x First value to compare
|
475 | * @param {number} y Second value to compare
|
476 | * @param {number} [epsilon] The maximum relative difference between x and y
|
477 | * If epsilon is undefined or null, the function will
|
478 | * test whether x and y are exactly equal.
|
479 | * @return {boolean} whether the two numbers are nearly equal
|
480 | */
|
481 | exports.nearlyEqual = function (x, y, epsilon) {
|
482 | // if epsilon is null or undefined, test whether x and y are exactly equal
|
483 | if (epsilon === null || epsilon === undefined) {
|
484 | return x === y;
|
485 | }
|
486 |
|
487 | if (x === y) {
|
488 | return true;
|
489 | }
|
490 |
|
491 | // NaN
|
492 | if (isNaN(x) || isNaN(y)) {
|
493 | return false;
|
494 | }
|
495 |
|
496 | // at this point x and y should be finite
|
497 | if (isFinite(x) && isFinite(y)) {
|
498 | // check numbers are very close, needed when comparing numbers near zero
|
499 | var diff = Math.abs(x - y);
|
500 | if (diff < exports.DBL_EPSILON) {
|
501 | return true;
|
502 | } else {
|
503 | // use relative error
|
504 | return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon;
|
505 | }
|
506 | }
|
507 |
|
508 | // Infinite and Number or negative Infinite and positive Infinite cases
|
509 | return false;
|
510 | }; |
\ | No newline at end of file |