Javascript format a decimal number to tree numbers after decimal - javascript

How can I format numbers like
0.00012006 to 0.00012
0.00004494 to 0.0000449
0.000000022732 to 0.0000000227 without becoming a number like 2.3e-8
I would like to know how I can change numbers like that in a fast/efficient way.
I would like to know how to convert those numbers but if someone knows how to format it only like that, I would like to know that too.

Use yourNumber.toFixed(numberOfDigitsAfterDot) like this:
function format(n) {
var _n = n;
// count the position of the first decimal
var count = 0;
do {
n = n * 10;
count++;
} while(n < 1);
return _n.toFixed(count + 2);
}
var num = 0.000000022732;
console.log(format(num));

You coud get the places of the number and add 2 on it for toFixed.
function three(v) {
var n = Math.floor(Math.log(v) / Math.LN10);
return v.toFixed(n < 2 ? 2 - n : 0);
}
var n = [0.00012006, 0.00004494, 0.000000022732, 0.100101, 0.1100001, 1.000001, 12000, 10, 1e10];
console.log(n.map(three));

Related

How to find the number of 1's in a binary representation of a number?

From other searches, I found that this problem is called 'Hamming Weight' or 'Population Count'. There are lot of answers out there given with so many statistics?
I need to find the solution in a simple way? Complexity is not a big deal.
Is there any in-built function in JavaScript like Java's Integer.bitCount?
I'm currently doing this as follows.
var binary = 3;
var original = binary;
var count = 0;
while(binary>0)
{
binary = binary >> 1 << 1;
if(original-binary==1)
count++;
original = binary >> 1;
binary = original;
}
Is there a better, more simple as well as elegant way for this?
try this
var binary = 10;
var result = binary.toString(2); //Converts to binary
var count = result.split(1);// count -1 is your answer
alert((result.split('1').length-1));
can also be written as
(binary.toString(2).split('1').length-1)
toString(2) : helps to split it in a base2 format which is binary, can do this in a range of 2- 36 (iam not sure about the range)
If you want to count 1 digit in binary representation we can use regular expression like this.
number.toString(2).match(/1/g).length
A simple way without using built-in functions:
function f(n){
let i = 0;
do if(n&1) ++i; while(n>>=1)
return i;
}
// example:
console.log(f(7)); // 3
function numOfOnes(n) {
if(n === 0) return n;
return (n & 1) + numOfOnes(n >>= 1);
}
Basically this approach belongs to recursive call.
It has the base condition when no number to evaluate. Otherwise it calls itself on (n >>= 1) and add last digit (n & 1) to result.
eg. 7 has binary representation 111 = 1+1+1 = 3
17 has binary representation 10001 = 1+0+0+0+1 = 2
function countOnesInDecimal(num) {
let count = 0;
let binary = num.toString(2);
const splitted = binary.split('');
for (const iterator of splitted) {
if (iterator === `1`) {
count += 1;
}
}
return count;
}
console.log(countOnesInDecimal(3));

How do i replace the first number?

I believe that it is simple, but currently it isn't working for me... Look what I need below:
seed = 9999;
seed[0] = 1;
seed; //now it's returning 9999, but I want 1999
There are another way to do?
seed is a Number, not a string. You either have to use it as string:
seed='9999';
seed[0]='1';
console.log(seed)//'1999'
Or you can apply a quick fix:
seed=9999;
seed-=8000;
console.log(seed)//1999
Update
You could also make a class to manage the number i that way:
function numArr() {
this.arr = [];
this.setNum = function (num) {
this.arr = [];
while (num > 10) {//while has digits left
this.arr.unshift(num % 10);//add digit to array
num = Math.floor(num / 10);//remove last digit from num
}
this.arr.unshift(num)//add the remaining digit
};
this.getNum = function () {
var num = 0;
for (var i = this.arr.length - 1; i >= 0; i--) {//for each digit
num += this.arr[i] * Math.pow(10, (this.arr.length - 1 - i))//add the digit*units
}
return num;
}
}
var seed= new numArr();
seed.setNum(9960);
seed.arr[0]=1;
console.log(seed.getNum())//1960
seed.setNum(seed.getNum()+1000);
console.log(seed.getNum())//2960
You can use regex like:
"9999".replace(/[\d]/,"1")
Disclaimer: I am offering an alternate view to problem but of course there is various options to resolve it.
As is mentioned above the seed is a number not an array ,so you can't do it as you doing it. Look at this:
var seed = (9999 + "").split(""), // Convert the number to string and split it
seed = ~~(seed[0] = "1", seed.join("")); // Now you can change the first digit then join it back to a string a if you want to you can also convert it back to number
console.log(seed); // 1999
try this
seed = 9999;
seed = seed.toString()
seed= 1+seed.substr(1, seed.length);
alert(seed);
seed = 9999;
var len = seed.toString().length;
var seedAllDigits = seed % (Math.pow(10,len-1));
var finalSeed = "1" + seedAllDigit;
Somethink like this will do the work..
Hope it make sense
9999 % 1000 + 1000 * 1 == 1999;

How to get first 2 non zero digits after decimal in javascript

I need to get the first 2 non zero digits from a decimal number. How can this be achieved?
Suppose I have number like 0.000235 then I need 0.00023, if the number is 0.000000025666 then my function should return 0.000000025.
Can any one have an idea of how this can be achieved in javascript?
The result should be a float number not a string.
Here are two faster solutions (see jsperf) :
Solution 1 :
var n = 0.00000020666;
var r = n.toFixed(1-Math.floor(Math.log(n)/Math.log(10)));
Note that this one doesn't round to the smallest value but to the nearest : 0.0256 gives 0.026, not 0.025. If you really want to round to the smallest, use this one :
Solution 2 :
var r = n.toFixed(20).match(/^-?\d*\.?0*\d{0,2}/)[0];
It works with negative numbers too.
var myNum = 0.000256
var i = 1
while(myNum < 10){
myNum *= 10
i *= 10
}
var result = parseInt(myNum) / i
With numbers that has that many decimals, you'd have to return a string, as any parsing as number would return scientific notation, as in 0.000000025666 would be 2.5666e-8
function round(n, what) {
var i = 0;
if (n < 1) {
while(n < 1) {
n = n*10;
i++;
}
}
return '0.' + (new Array(i)).join('0') + n.toFixed(what).replace('.','').slice(0,-1);
}
FIDDLE

Fibonacci Sequence - Find the number of digits - JavaScript

So, I have successfully written the Fibonacci sequence to create an array with the sequence of numbers, but I need to know the length (how many digits) the 500th number has.
I've tried the below code, but its finding the length of the scientific notation (22 digits), not the proper 105 it should be returning.
Any ideas how to convert a scientific notation number into an actual integer?
var fiblength = function fiblength(nth) {
var temparr = [0,1];
for(var i = 2; i<=nth; i++){
var prev = temparr[temparr.length-2],
cur = temparr[temparr.length-1],
next = prev + cur;
temparr.push(next);
}
var final = temparr[temparr.length-1].toString().length;
console.log(temparr[temparr.length-1]);
return final;
};
a = fiblength(500);
console.log(a);
Why not use the simple procedure of dividing the number by 10 until the number is less than 1.
Something as simple as this should work (a recursive def obv works as well)
function getDigits(n) {
var digits = 0;
while(n >= 1) {
n/=10;
digits += 1;
}
return digits;
}
getDigits(200);//3
getDigits(3.2 * 10e20);//=>22
Here's a solution in constant time:
function fiblength(n) {
return Math.floor((n>1)?n*.2089+.65051:1);
}
Let's explain how I arrived to it.
All previous solutions will probably not work for N>300 unless you have a BigNumber library in place. Also they're pretty inneficient.
There is a formula to get any Fibonacci number, which uses PHI (golden ratio number), it's very simple:
F(n) = ABS((PHI^n)/sqrt(5))
Where PHI=1.61803399 (golden ratio, found all over the fibonacci sequence)
If you want to know how many digits a number has, you calculate the log base 10 and add 1 to that. Let's call that function D(n) = log10(n) + 1
So what you want fiblength to be is in just the following function
fiblength(n) = D(F(n)) // number of digits of a fibonacci number...
Let's work it out, so you see what the one liner code will be like once you use math.
Substitute F(n)
fiblength(n) = D(ABS((PHI^n)/sqrt(5)))
Now apply D(n) on that:
fiblength(n) = log10(ABS((PHI^n)/sqrt(5))) + 1
So, since log(a/b) = log(a) - log(b)
fiblength(n) = log10(ABS((PHI^n))) - log10(sqrt(5))) + 1
and since log(a^n) = n * log(a)
fiblength(n) = n*log10(PHI) - log10(sqrt(5))) + 1
Then we evaluate those logarithms since they're all on constants
and add the special cases of n=0 and n=1 to return 1
function fiblength(n) {
return Math.floor((n>1)?n*.2089+.65051:1);
}
Enjoy :)
fiblength(500) => 105 //no iterations necessary.
Most of the javascript implementations, internally use 64 bit numbers. So, if the number we are trying to represent is very big, it uses scientific notation to represent those numbers. So, there is no pure "javascript numbers" based solution for this. You may have to look for other BigNum libraries.
As far as your code is concerned, you want only the 500th number, so you don't have to store the entire array of numbers in memory, just previous and current numbers are enough.
function fiblength(nth) {
var previous = 0, current = 1, temp;
for(var i = 2; i<=nth; i++){
temp = current;
current = previous + current;
previous = temp;
}
return current;
};
My Final Solution
function fiblength(nth) {
var a = 0, b = 1, c;
for(var i=2;i<=nth;i++){
c=b;
b=a+b;
a=c;
}
return Math.floor(Math.log(b)/Math.log(10))+1;
}
console.log(fiblength(500));
Thanks for the help!!!
The problem is because the resulting number was converted into a string before any meaningful calculations could be made. Here's how it could have been solved in the original code:
var fiblength = function fiblength(nth) {
var temparr = [0,1];
for(var i = 2; i<=nth; i++){
var prev = temparr[temparr.length-2],
cur = temparr[temparr.length-1],
next = prev + cur;
temparr.push(next);
}
var x = temparr[temparr.length-1];
console.log(x);
var length = 1;
while (x > 1) {
length = length + 1;
x = x/10;
}
return length;
};
console.log ( fiblength(500) );

javascript - generate a new random number

I have a variable that has a number between 1-3.
I need to randomly generate a new number between 1-3 but it must not be the same as the last one.
It happens in a loop hundreds of times.
What is the most efficient way of doing this?
May the powers of modular arithmetic help you!!
This function does what you want using the modulo operator:
/**
* generate(1) will produce 2 or 3 with probablity .5
* generate(2) will produce 1 or 3 with probablity .5
* ... you get the idea.
*/
function generate(nb) {
rnd = Math.round(Math.random())
return 1 + (nb + rnd) % 3
}
if you want to avoid a function call, you can inline the code.
Here is a jsFiddle that solves your problem : http://jsfiddle.net/AsMWG/
I've created an array containing 1,2,3 and first I select any number and swap it with the last element. Then I only pick elements from position 0 and 1, and swap them with last element.
var x = 1; // or 2 or 3
// this generates a new x out of [1,2,3] which is != x
x = (Math.floor(2*Math.random())+x) % 3 + 1;
You can randomly generate numbers with the random number generator built in to javascript. You need to use Math.random().
If you're push()-ing into an array, you can always check if the previously inserted one is the same number, thus you regenerate the number. Here is an example:
var randomArr = [];
var count = 100;
var max = 3;
var min = 1;
while (randomArr.length < count) {
var r = Math.floor(Math.random() * (max - min) + min);
if (randomArr.length == 0) {
// start condition
randomArr.push(r);
} else if (randomArr[randomArr.length-1] !== r) {
// if the previous value is not the same
// then push that value into the array
randomArr.push(r);
}
}
As Widor commented generating such a number is equivalent to generating a number with probability 0.5. So you can try something like this (not tested):
var x; /* your starting number: 1,2 or 3 */
var y = Math.round(Math.random()); /* generates 0 or 1 */
var i = 0;
var res = i+1;
while (i < y) {
res = i+1;
i++;
if (i+1 == x) i++;
}
The code is tested and it does for what you are after.
var RandomNumber = {
lastSelected: 0,
generate: function() {
var random = Math.floor(Math.random()*3)+1;
if(random == this.lastSelected) {
generateNumber();
}
else {
this.lastSelected = random;
return random;
}
}
}
RandomNumber.generate();

Categories

Resources