basically, you have to multiply the near amount (e.g. 1.25) by a large number first (e.g. 1000000) in order to preserve the fraction before you convert the number to Yocto using toYoctob128(u128.from(amount))
.
and after the successful conversion, you can use u128.div()
(e.g. u128.div(amountInU128, u128.from(1000000))
) to get the correct value.
P.S.
The larger the number you multiply by first the more accurate the conversion will be but be careful not to exceed the number
and u128
limit.
Here is a complete example:
Contract Class:
nearToYocto(x: string): u128 {
let amountBase = (parseFloat(x) * BASE_TO_CONVERT);
return u128.div(toYoctob128(u128.from(amountBase)), u128.from(BASE_TO_CONVERT));
}
utils:
export const BASE_TO_CONVERT = 1000000.0;
export function toYoctob128(amount: u128): u128 {
return u128.mul(ONE_NEAR, amount)
}