feat(StatusQ): AmountsArithmetic - utility method added for creating num from exponent

This commit is contained in:
Michał Cieślak 2024-07-17 17:34:44 +02:00 committed by Michał
parent b9790c9797
commit 84be1d9da7
1 changed files with 13 additions and 9 deletions

View File

@ -31,18 +31,11 @@ QtObject {
console.log(0.07 * 10**18) // 70000000000000010 - incorrect console.log(0.07 * 10**18) // 70000000000000010 - incorrect
console.log(AmountsArithmetic.fromNumber(0.07, 18)) // 70000000000000000 - correct console.log(AmountsArithmetic.fromNumber(0.07, 18)) // 70000000000000000 - correct
\endqml \endqml
The amount is assumed to be an integer, therefore the accuracy after the
decimal point cannot be greater than the indicated multiplier. Otherwise,
a warning will be printed.
*/ */
function fromNumber(number, multiplier = 0) { function fromNumber(number, multiplier = 0) {
console.assert(!isNaN(number) && Number.isInteger(multiplier) console.assert(!isNaN(number) && Number.isInteger(multiplier)
&& multiplier >= 0) && multiplier >= 0)
const amount = new Big.Big(number).times(10 ** multiplier) return new Big.Big(number).times(fromExponent(multiplier))
// TODO: restore assert when permissions handled as bigints
// console.assert(amount.eq(amount.round()))
return amount
} }
/*! /*!
@ -68,7 +61,7 @@ QtObject {
amount = fromString(amount) amount = fromString(amount)
console.assert(amount instanceof Big.Big) console.assert(amount instanceof Big.Big)
return amount.div(10 ** multiplier).toNumber() return amount.div(fromExponent(multiplier)).toNumber()
} }
/*! /*!
@ -99,6 +92,17 @@ QtObject {
} }
} }
/*!
\qmlmethod AmountsArithmetic::fromExponent(exponent)
\brief Construct a number 10^exponent in a safe manner.
*/
function fromExponent(exponent) {
console.assert(Number.isInteger(exponent))
const num = new Big.Big(1)
num.e += exponent
return num
}
/*! /*!
\qmlmethod AmountsArithmetic::times(amount, multiplier) \qmlmethod AmountsArithmetic::times(amount, multiplier)
\brief Returns an amount whose value is the value of num1 times num2. \brief Returns an amount whose value is the value of num1 times num2.