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