Skip to content

Commit

Permalink
Fix parsing amount based on language of user
Browse files Browse the repository at this point in the history
  • Loading branch information
behrang committed Jan 15, 2025
1 parent d30ae6e commit 0d6502d
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/Model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export class Model {
timeoutReferralStats?: ReturnType<typeof setTimeout>
timeoutHipoGauge?: ReturnType<typeof setTimeout>

readonly numberParser = new NumberParser(navigator.language)

readonly dedustSwapUrl = 'https://dedust.io/swap/hTON/TON'
readonly dedustPoolUrl = 'https://dedust.io/pools/EQBWsAdyAg-8fs3G-m-eUBCXZuVaOldF5-tCMJBJzxQG7nLX'
readonly stonSwapUrl = 'https://app.ston.fi/swap?chartVisible=false&ft=hTON&tt=TON'
Expand Down Expand Up @@ -323,7 +325,7 @@ export class Model {
}

get amountInNano() {
const amount = this.amount.trim()
const amount = this.numberParser.parse(this.amount).toString()
try {
return toNano(amount)
} catch {
Expand Down Expand Up @@ -1209,6 +1211,30 @@ export class Model {
}
}

class NumberParser {
#group: RegExp
#decimal: RegExp
#numeral: RegExp
#index: (substring: string) => string
constructor(locale: string) {
const parts = new Intl.NumberFormat(locale).formatToParts(12345.6)
const numerals = [...new Intl.NumberFormat(locale, { useGrouping: false }).format(9876543210)].reverse()
const index = new Map(numerals.map((d, i) => [d, i]))
this.#group = new RegExp(`[${(parts.find((d) => d.type === 'group') ?? parts[0]).value}]`, 'g')
this.#decimal = new RegExp(`[${(parts.find((d) => d.type === 'decimal') ?? parts[0]).value}]`)
this.#numeral = new RegExp(`[${numerals.join('')}]`, 'g')
this.#index = (d) => (index.get(d) ?? '').toString()
}
parse(input: string) {
const result = input
.trim()
.replace(this.#group, '')
.replace(this.#decimal, '.')
.replace(this.#numeral, this.#index)
return result ? +result : NaN
}
}

export function formatCompact1Fraction(n: number): string {
return n.toLocaleString(undefined, { notation: 'compact', maximumFractionDigits: 1 })
}
Expand Down

0 comments on commit 0d6502d

Please sign in to comment.