Files
dashboards/src/utils/price.ts
T

36 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const PERSIAN_DIGITS = '۰۱۲۳۴۵۶۷۸۹'
const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩'
export function toEnglishDigits(value: string) {
return value
.replace(/[۰-۹]/g, (digit) => String(PERSIAN_DIGITS.indexOf(digit)))
.replace(/[٠-٩]/g, (digit) => String(ARABIC_DIGITS.indexOf(digit)))
}
/** Keep only digits from any price-like string. */
export function parsePriceDigits(value: string): string {
return toEnglishDigits(value).replace(/\D/g, '')
}
export function parsePriceNumber(value: string): number | null {
const digits = parsePriceDigits(value)
if (!digits) return null
const number = Number(digits)
return Number.isNaN(number) ? null : number
}
/** Display value for price inputs (Persian thousand separators). */
export function formatPriceInput(value: string | number | null | undefined) {
if (value === null || value === undefined || value === '') return ''
const digits =
typeof value === 'number'
? String(Math.trunc(Math.abs(value)))
: parsePriceDigits(value)
if (!digits) return ''
return new Intl.NumberFormat('fa-IR').format(Number(digits))
}
export function formatPrice(value: number) {
return new Intl.NumberFormat('fa-IR').format(value)
}