diff --git a/packages/neuron-wallet/src/utils/sudt-value-to-amount.ts b/packages/neuron-wallet/src/utils/sudt-value-to-amount.ts index 4791a68544..37c1ed2c03 100644 --- a/packages/neuron-wallet/src/utils/sudt-value-to-amount.ts +++ b/packages/neuron-wallet/src/utils/sudt-value-to-amount.ts @@ -1,32 +1,11 @@ -const sudtValueToAmount = (value: string | null | undefined = '0', decimal: string | null | undefined = '') => { - if (value === null || value === '0') { - return '+0' - } - - if (decimal === null || decimal === undefined || Number.isNaN(+value)) { - return '--' - } - - let sign = '+' - if (value.startsWith('-')) { - sign = '-' - } - - const unsignedValue = value.replace(/^-?0*/, '') - - const dec = +decimal - if (dec === 0) { - return +unsignedValue ? `${sign}${unsignedValue}` : '+0' - } - let unsignedSUDTValue = '' - if (unsignedValue.length <= dec) { - unsignedSUDTValue = `0.${unsignedValue.padStart(dec, '0')}`.replace(/\.?0+$/, '') - } else { - const decimalFraction = `.${unsignedValue.slice(-dec)}`.replace(/\.?0+$/, '') - const int = unsignedValue.slice(0, -dec).replace(/\^0+/, '') - unsignedSUDTValue = `${int}${decimalFraction}` - } - return `${sign}${unsignedSUDTValue}` +import { formatUnit } from '@ckb-lumos/bi' + +const sudtValueToAmount = (value: string | null = '0', decimal: string | null = '') => { + return value === null || value === '0' + ? '+0' + : decimal === null || Number.isNaN(+value) || Number.isNaN(+decimal) + ? '--' + : `${+value >= 0 ? '+' : ''}${formatUnit(BigInt(value), +decimal)}` } export default sudtValueToAmount diff --git a/packages/neuron-wallet/tests/utils/sudt-value-to-amount/fixtures.json b/packages/neuron-wallet/tests/utils/sudt-value-to-amount/fixtures.json index d98624cd1e..f4b1c9c6e5 100644 --- a/packages/neuron-wallet/tests/utils/sudt-value-to-amount/fixtures.json +++ b/packages/neuron-wallet/tests/utils/sudt-value-to-amount/fixtures.json @@ -14,11 +14,21 @@ "decimal": "12", "expected": "+0" }, + "null value and null decimal": { + "value": null, + "decimal": null, + "expected": "+0" + }, "zero value": { "value": "0", "decimal": "1", "expected": "+0" }, + "zero value and null decimal": { + "value": "0", + "decimal": null, + "expected": "+0" + }, "negative value": { "value": "-1", "decimal": "1",