forked from cryptobuks1/JsWallet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumbers.js
More file actions
95 lines (73 loc) · 2.59 KB
/
Copy pathnumbers.js
File metadata and controls
95 lines (73 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'use strict'
// modified from accounting.js
function parseNum (value, decimalSep) {
if (value == null) return NaN
decimalSep = decimalSep || '.'
// Return the value as-is if it's already a number:
if (typeof value === 'number') return value
// build regex to strip out everything except digits, decimal point and minus sign:
var regex = new RegExp('[^0-9-' + decimalSep + ']', ['g'])
var unformatted = value.toString() // explicitly convert to string
unformatted = unformatted
// .replace(/\((.*)\)/, '-$1') // replace bracketed values with negatives
.replace(regex, '') // strip out any cruft
.replace(decimalSep, '.') // make sure decimal point is standard
unformatted = parseFloat(unformatted)
return unformatted
}
module.exports.parseNum = parseNum;
/* global Intl */
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
const defaultOptions = {
nanZero: true,
locale: 'en-US',
localeMatcher: 'best fit',
useGrouping: true, // grouping separator determined by locale
maximumFractionDigits: 15
// OTHER
// minimumIntegerDigits
// minimumFractionDigits
// maximumFractionDigits
// minimumSignificantDigits
// maximumSignificantDigits
}
const formatNum = (number, opts) => {
console.log("[format-number]")
opts = renameKeyShortcuts(Object.assign({}, defaultOptions, opts))
number = parseNum(number)
if (isNaN(number)) {
console.log("isNaN", number);
if (opts.nanZero === false) return number;
else number = 0
}
const nf = new Intl.NumberFormat([opts.locale], Object.assign({}, opts, { style: 'decimal' }))
return nf.format(number)
}
const renameKeyShortcuts = (opts) => {
Object.keys(opts).forEach((key) => {
expandMin(opts, key)
expandMax(opts, key)
})
Object.keys(opts).forEach((key) => addDigits(opts, key))
return opts
}
const expandMin = (opts, key) => expand(opts, key, 'min', 'minimum')
const expandMax = (opts, key) => expand(opts, key, 'max', 'maximum')
const expand = (opts, key, shorthand, full) => {
if (!key.includes(full) && key.startsWith(shorthand)) {
replaceKey(opts, key, key.replace(shorthand, full))
}
}
const addDigits = (opts, key) => {
if (
(key.startsWith('minimum') || key.startsWith('maximum')) &&
!key.endsWith('Digits')
) {
replaceKey(opts, key, key + 'Digits')
}
}
const replaceKey = (obj, oldKey, newKey) => {
obj[newKey] = obj[oldKey]
delete obj[oldKey]
}
module.exports.formatNum = formatNum;