/
index.ts
49 lines (44 loc) · 1.04 KB
/
index.ts
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
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'
import { resolveUnref } from '../resolveUnref'
import type { MaybeComputedRef } from '../utils'
export interface UseToNumberOptions {
/**
* Method to use to convert the value to a number.
*
* @default 'parseFloat'
*/
method?: 'parseFloat' | 'parseInt'
/**
* The base in mathematical numeral systems passed to `parseInt`.
* Only works with `method: 'parseInt'`
*/
radix?: number
/**
* Replace NaN with zero
*
* @default false
*/
nanToZero?: boolean
}
/**
* Computed reactive object.
*/
export function useToNumber(
value: MaybeComputedRef<number | string>,
options: UseToNumberOptions = {},
): ComputedRef<number> {
const {
method = 'parseFloat',
radix,
nanToZero,
} = options
return computed(() => {
let resolved = resolveUnref(value)
if (typeof resolved === 'string')
resolved = Number[method](resolved, radix)
if (nanToZero && isNaN(resolved))
resolved = 0
return resolved
})
}