Reputation: 724
I'm currently working with decimal points but Javascript seems to be rounding down all the time.
For example, here's one of the calculations I need done:
(1 + 0.05) ^ (1/12)
This should return 1.0040741237836483016054196026721 however all I'm getting is 1.
I've tried using the Big.js library but it's still only returning me 1 and I need those decimal points to have an accurate result, is there a way to specify the number of decimal positions I want?
Upvotes: 1
Views: 355
Reputation: 5075
The ^
symbol has bitwise XOR semantics in javascript. See here.
The following code snippet shows you how to obtain the correct result:
console.log(`(1 + 0.05) ^ (1/12) = ${Math.pow((1 + 0.05), (1/12))}`);
Upvotes: 4
Reputation: 681
You should always use Math (MDN oficial source) Library to make calculations. You can use Pow(val, exponential)
function to your advantage.
If you have 1/2 then you can say it's 2^(-1). This way you can always translate a division to an exponential
Javascript has some issues with precision, and you will have a hard time dealing with floating points.
var amount = (1 + 0.05) ^ (1/12);
var amountPow = Math.pow(1 + 0.05, Math.pow(12,-1));
console.log((1 + 0.05) ^ (1/12)); // Normal
console.log(amountPow); // Exponential function Math
Upvotes: 1
Reputation: 10899
As noted in another answer, you can use vanilla JS but if you need to perform mathematical operations with precision than you can look into libraries like decimal.js to aid with maintaining that precision.
const vanJS = Math.pow(1 + 0.05, 1/12);
const decJS = Decimal.pow(1 + 0.05, 1/12).toPrecision(20);
console.log({ vanJS, decJS });
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.0.1/decimal.min.js"></script>
Upvotes: 1