diff --git a/packages/ui/src/common/components/forms/InputNumber.tsx b/packages/ui/src/common/components/forms/InputNumber.tsx index d809874eb0..7bd5fd48dd 100644 --- a/packages/ui/src/common/components/forms/InputNumber.tsx +++ b/packages/ui/src/common/components/forms/InputNumber.tsx @@ -4,7 +4,7 @@ import { useFormContext, Controller } from 'react-hook-form' import NumberFormat, { NumberFormatValues, SourceInfo } from 'react-number-format' import styled from 'styled-components' -import { asBN, powerOf10, whenDefined } from '@/common/utils' +import { asBN, divToNum, whenDefined } from '@/common/utils' import { Input, InputProps } from './InputComponent' @@ -55,7 +55,7 @@ export const InputNumber = React.memo(({ name, isInBN = false, ...props }: Numbe return } - const exp = props.decimalScale ?? 0 + const exp = 10 ** (props.decimalScale ?? 0) return ( { - const num = isInBN ? asBN(value).toNumber() : value // TODO convert to number safely - return String(num / 10 ** exp) + if (value === undefined || value === null) { + return '' + } + const numValue = isInBN ? divToNum(asBN(value), exp) : value / exp + return numValue.toFixed(props.decimalScale ?? 0) })} - onChange={(_, numValue) => { - const value = isInBN ? new BN(numValue).mul(powerOf10(exp)) : numValue * 10 ** exp + onChange={(event, numValue) => { + if (!event) return + if (event.target.value === '') { + return field.onChange(null) + } + const value = isInBN ? new BN(numValue).muln(exp) : numValue * exp return field.onChange(value) }} onBlur={field.onBlur} diff --git a/packages/ui/src/common/utils/bn.ts b/packages/ui/src/common/utils/bn.ts index 0a11b6c24e..ed268099cd 100644 --- a/packages/ui/src/common/utils/bn.ts +++ b/packages/ui/src/common/utils/bn.ts @@ -13,3 +13,8 @@ export const sumBN = (a: BN | undefined, b: BN | undefined): BN => new BN(a ?? 0 export const powerOf10 = (value: any) => BN_TEN.pow(asBN(value)) export const powerOf2 = (value: any) => BN_TWO.pow(asBN(value)) + +export const divToNum = (dividend: BN, divisor: number): number => { + const div = dividend.divmod(new BN(divisor)) + return div.div.toNumber() + div.mod.toNumber() / divisor +}