8000 feat(number): support E number when format · kdt310722/utils@a189cec · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Commit a189cec

Browse files
committed
feat(number): support E number when format
1 parent 34f36b8 commit a189cec

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/number/format.ts

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,29 @@
1-
import type { FormatOptions, Numberish } from './types'
1+
import { rtrim } from '../string'
2+
import type { FormatOptions, NumberString, Numberish } from './types'
3+
4+
export function convertExponentialToString(num: Numberish) {
5+
const str = num.toString()
6+
7+
if (!str.includes('e')) {
8+
return str as NumberString
9+
}
10+
11+
if (!str.includes('e-')) {
12+
return BigInt(num).toString() as NumberString
13+
}
14+
15+
const [base, exp] = str.split('e-').map(Number)
16+
const precision = base.toString().replace('.', '').length + exp
17+
18+
return rtrim(Number.parseFloat(str).toFixed(precision), '0') as NumberString
19+
}
220

321
export function format(number: Numberish, options: FormatOptions = {}) {
422
let leadingZerosCount = 0
523
let { maximumFractionDigits = 4, groupFractionLeadingZeros = false } = options
624

25+
number = convertExponentialToString(number)
26+
727
const { exactFractionWhenZero = true, maximumFractionLeadingZeros = maximumFractionDigits } = options
828
const [integerPart, fractionPart = '0'] = String(number).split('.')
929

src/number/types.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
export type Numberish = `${number}` | 'Infinity' | '-Infinity' | '+Infinity' | number | bigint
1+
export type NumberString = `${number}` | 'Infinity' | '-Infinity' | '+Infinity'
2+
3+
export type Numberish = NumberString | number | bigint
24

35
export interface FormatOptions extends Intl.NumberFormatOptions {
46
locales?: string | string[]

0 commit comments

Comments
 (0)
0