initial
This commit is contained in:
89
layers/shared/utils/money.ts
Normal file
89
layers/shared/utils/money.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import Decimal from 'decimal.js'
|
||||
|
||||
const CURRENCY_SYMBOL: Record<string, string> = {
|
||||
RUB: '₽',
|
||||
USD: '$',
|
||||
EUR: '€',
|
||||
}
|
||||
|
||||
const DEFAULT_FORMAT: string = '{amount} {currency}'
|
||||
const CURRENCY_FORMAT: Record<string, string> = {
|
||||
USD: '{currency}{amount}',
|
||||
RUB: '{amount}{currency}',
|
||||
EUR: '{currency}{amount}',
|
||||
}
|
||||
|
||||
const DEFAULT_EXPONENT: number = 2
|
||||
const CURRENCY_EXPONENT: Record<string, number> = {
|
||||
BTC: 6,
|
||||
USDT: 2,
|
||||
}
|
||||
|
||||
function getSymbol(currency: string): string {
|
||||
return CURRENCY_SYMBOL[currency] ?? currency
|
||||
}
|
||||
|
||||
function getFormat(currency: string): string {
|
||||
return CURRENCY_FORMAT[currency] ?? DEFAULT_FORMAT
|
||||
}
|
||||
|
||||
function getExponent(currency: string): number {
|
||||
return CURRENCY_EXPONENT[currency] ?? DEFAULT_EXPONENT
|
||||
}
|
||||
|
||||
function format(value: Decimal.Value, currency: string): string {
|
||||
const exponent = getExponent(currency)
|
||||
|
||||
try {
|
||||
return new Decimal(value).toFixed(exponent)
|
||||
}
|
||||
catch {
|
||||
return new Decimal(0).toFixed(exponent)
|
||||
}
|
||||
}
|
||||
|
||||
function fullFormat(value: Decimal.Value, currency: string, showCurrency = true, approximately = false): string {
|
||||
let result = ''
|
||||
let decimalValue: Decimal.Instance
|
||||
const exponent = getExponent(currency)
|
||||
|
||||
try {
|
||||
decimalValue = new Decimal(value)
|
||||
}
|
||||
catch {
|
||||
decimalValue = new Decimal(0)
|
||||
}
|
||||
|
||||
value = decimalValue.toFixed(exponent)
|
||||
|
||||
if (approximately && !decimalValue.isZero())
|
||||
result = '~'
|
||||
|
||||
if (showCurrency) {
|
||||
const symbol = getSymbol(currency)
|
||||
const format = getFormat(currency)
|
||||
|
||||
result += format.replace('{amount}', value).replace('{currency}', symbol)
|
||||
}
|
||||
else {
|
||||
result += value
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
function convert(amount: Decimal.Value, rate: Decimal.Value, isTurnRate = true) {
|
||||
if (isTurnRate)
|
||||
return Decimal.mul(amount, rate)
|
||||
else
|
||||
return Decimal.div(amount, rate)
|
||||
}
|
||||
|
||||
export const $money = {
|
||||
getSymbol,
|
||||
getFormat,
|
||||
getExponent,
|
||||
format,
|
||||
fullFormat,
|
||||
convert,
|
||||
}
|
||||
Reference in New Issue
Block a user