dhj
dhj

Reputation: 4805

How to convert an integer with n decimal places to a float

I have this integer

7839486009458047182

I have a variable that tells me this number should have n decimal places (In this case 18)

How can I change it to 7.839486009458047182

(If React has this as a method I could use in a template that's even better!)

Upvotes: 0

Views: 277

Answers (2)

lejlun
lejlun

Reputation: 4419

You can divide the integer by 10 raised to the number of decimal places.

let integer = 7839486009458047182

function setDP(number, decimalPlaces) {
  return number / 10 ** decimalPlaces
}

console.log(setDP(integer, 18))

Upvotes: 1

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

If you're not too bothered about precision, you can simply divide the integer by 10 ** decimals, for example:

console.log(7839486009458047182 / (10 ** 18));
// ^ 7.839486009458047

Mind that floats have limited precision. If precision is key, keep it as an integer (or bigint). If it's just for display purposes, then a small amount of imprecision shouldn't be an issue.

Upvotes: 1

Related Questions