0

I am building a simple crypto currency conversion page and it requires to divide and multiply rates in most cases. The error I am getting is cases when i divide 1 by 5198000, I get 1.923816852635629e-7 in result I realized that even the calculators gives that same out put. How can I fix this in JavaScript?

The code below returns 1.923816852635629e-7 in console var num1=1; var num2=5198000;

var output=num1/num2; console.log(output);

Is there a way to convert or bypass this.

karel
  • 5,489
  • 46
  • 45
  • 50
  • Does this answer your question? [How to avoid scientific notation for large numbers in JavaScript?](https://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) – GirkovArpa Sep 20 '20 at 04:08
  • 1
    What leads you to believe that this is an error? What result do you expect to get? – Robert Lozyniak Sep 24 '20 at 02:17

1 Answers1

0

This is scientific notation. The decimal format would be 0.0000001923816852635629. Code to generate this string to display in the UI for negative exponents is roughly:

var foo = 1/5198000; // scientific value
var sciStr= '' + foo; //cast scientific value to string
var w = '' + sciStr.substring(0, sciStr.indexOf('e')); // extract numerical value
var exp = Math.abs(parseInt(sciStr.substring(sciStr.indexOf('e')+1, sciStr.length))); // get absolute numerical exponent value

// write appropriate number of 0's
var expStr= '0.';
for (var i = 1; i < exp; i++) {
    expStr+='0'; 
}
w = w.substring(0,1)+w.substring(2,w.length) // strip decimal from scientific value

console.log('the decimal form is:')
console.log(expStr+w) // outputs '0.0000001923816852635629'

You will need to modify this code to work for positive exponents (adding 0's at the end)

However, this should be stressed that the final result is a string, not a numerical value, so it won't be very useful if you need to perform further mathematical operations with it.

Our_Benefactors
  • 3,220
  • 3
  • 21
  • 27