Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array.push() and .toFixed – javascript

I am creating program for generating random numbers using javascript.
While writing the code, I observed this strange behaviour;(Or atleast strange to me).

Variable are:

  • M is Maximum of range in which random number has to be generated.(inclusive)
  • m is Minimum of range in which random number has to be generated.(inclusive)
  • q is Level of decimals; i.e, for 0.9, it is 1; for 0.09 and 0.99 it is 2 etc.
  • q1 is 10^q; i.e., if q=1, q1=10; if q=2, q1=100 etc.

And somewhere among my codes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array.push(m+(((Math.round(((Math.random()*(M-m)) + (Number.EPSILON))) * q1) / q1))).toFixed(q);

This worked perfectly as intended.
But then I realised .toFixed(q) is outside the array.push;
I mean it is like

array.push(/*some code here*/).toFixed(/*another code here*/);

Even though it is working as intended I am curious that whether array.push() has method .toFixed().
So when I put:

array.push((m+(((Math.round(((Math.random()(M-m)) + (Number.EPSILON))) * q1) / q1))).toFixed(q));

and q=3 The result has last 3 digits as 0. For example:9.000.

So ultimately my questions are:

  1. Why didn’t my code work as intended when I put .toFixed() inside parenthesis of array.push()?
  2. Does array.push() has a method .toFixed()?

Sorry for my English if something is wrong, English is not my native tongue.
You can see my full code here:
https://github.com/vinob4u/vinob4u.github.io/blob/main/BlockRandom.html

>Solution :

Why didn’t my code work as intended when I put .toFixed() inside parenthesis of array.push()?

The purpose of toFixed is to convert a number to a string with the specified number of decimal places.

You said 9..toFixed(3) so it expressed 9 to three decimal places, which is "9.000".

It’s generally more useful when presenting numbers with a high degree of precision to something readable (e.g. 1.234567890.toFixed(3) would be "1.234").

You seem to want 9 / Math.pow(10, 3).

Does array.push() has a method .toFixed()?

The return value of array.push() is a number (specifically The new length property of the object upon which the method was called).

Numbers have a toFixed method.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading