lbry-desktop/ui/util/format-credits.js

52 lines
1.5 KiB
JavaScript
Raw Permalink Normal View History

2022-05-06 15:31:36 +02:00
import { getFormatter } from './intlNumberFormat';
export function formatCredits(amount, precision, shortFormat = false) {
const language = localStorage.getItem('language') || undefined;
2022-04-26 17:28:23 +02:00
const actualAmount = Number(amount);
const safePrecision = Math.min(20, Math.max(1, precision || 0));
if (Number.isNaN(actualAmount) || actualAmount === 0) return '0';
2022-04-26 17:28:23 +02:00
if (shortFormat) {
2022-05-06 15:31:36 +02:00
const formatter = getFormatter(language, {
2022-04-26 17:28:23 +02:00
minimumFractionDigits: safePrecision,
maximumFractionDigits: safePrecision,
roundingIncrement: 5,
// Display suffix (M, K, etc.)
notation: 'compact',
compactDisplay: 'short',
});
return formatter.format(actualAmount);
}
2022-05-06 15:31:36 +02:00
const formatter = getFormatter(language, {
2022-04-26 17:28:23 +02:00
minimumFractionDigits: safePrecision,
maximumFractionDigits: safePrecision,
roundingIncrement: 5,
});
return formatter.format(actualAmount);
}
export function formatFullPrice(amount, precision = 1) {
let formated = '';
const quantity = amount.toString().split('.');
const fraction = quantity[1];
if (fraction) {
const decimals = fraction.split('');
const first = decimals.filter((number) => number !== '0')[0];
const index = decimals.indexOf(first);
// Set format fraction
formated = `.${fraction.substring(0, index + precision)}`;
}
return parseFloat(quantity[0] + formated);
}
export function creditsToString(amount) {
const creditString = parseFloat(amount).toFixed(8);
return creditString;
}