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