Per 'e' in javascript numbers I would like to use 'e' notation:
Right now I'm doing:
const USD_DECIMALS = 2
const USD = 1e2
As you can see I'm duplicating the number 2
. When I'd like to do is something like:
const USD_DECIMALS = 2
const USD = 1e[USD_DECIMALS]
Is this possible? Maybe using the Number()
constructor or similar?
CodePudding user response:
You could make a string out of "1e2" and then run it through Number.
const USD_DECIMALS = 2
const USDString = `1e${USD_DECIMALS}`;
const USD = Number(USDString);
console.log(USD);
CodePudding user response:
Not directly (without building a dynamic string, but then that's not direct either), but since 1e2
means 1 times 10², you can use either 1 * Math.pow(10, USD_DECIMALS)
OR 1 * 10**USD_DECIMALS
to do the same thing dynamically:
const USD_DECIMALS = 2;
const USD = 1 * 10**USD_DECIMALS;
// Or: const USD = 1 * Math.pow(10, USD_DECIMALS);
Live Example:
console.log("Various ways to get 10²:");
console.log(1e2);
const USD_DECIMALS = 2;
console.log(1 * Math.pow(10, USD_DECIMALS));
console.log(1 * 10**USD_DECIMALS);
console.log("Just for completeness, 10³:");
console.log(1e3);
const USD_DECIMALS3 = 3;
console.log(1 * Math.pow(10, USD_DECIMALS3));
console.log(1 * 10**USD_DECIMALS3);
.as-console-wrapper {
max-height: 100% !important;
}
(Side note: you sometimes need ()
around **
expressions where you may not expect to, such as in -1 ** 10
, but not in the above.)
CodePudding user response:
The N
eM
is for the order of magnitude (N*10^M). What you can do is just
n=n*(10**m)
If you actually want to control the number of decimals you have to round.