This question already has answers here:
How to deal with big numbers in javascript [duplicate]
(3 answers)
Closed 8 years ago.
I need to generate a 12 digit and 13 decimals float value like this:
123438767411.238792938
How can I do that in Javascript/Jquery? Is it possible to generate this code using JavaScript?
I was trying like this:
v1 = Math.floor((Math.random()*10000000000)+1);
v2 = Math.floor((Math.random()*100000000)+1);
v = v1.toString() + "." + v2.toString();
But this is not working!
(assuming you mean in the form of a string, not as a number, because IEEE 754 can't have that many significant digits)
must the integer part be 12 digits or can it be 1 or 123? If it can be 12 digits or shorter, then it can be
(Math.floor (Math.random() * Math.pow(10,12))
+ (Math.floor (Math.random() * Math.pow(10,13))
/ Math.pow(10,13)).toString().substring(1))
note that the above could have an issue when the decimal part turns out to be 0, although the chance is really small. (then the .0 part is gone, although we can use a conditional to add it when it is so). Or we can treat the decimal part 123 not as .0000000000123 but as .123 and use:
(Math.floor (Math.random() * Math.pow(10,12))
+ "." + Math.floor (Math.random() * Math.pow(10,13)))
But it depends whether we care about 123 becoming .123 and 1230 also becoming .1230 because if we do care about it, we can say .123 is the same as .1230.
Also, if we want to have the form such as 000042987017.0790946977900 as well, so that it is always 12 digit integer and 13 digit decimal, then either we can do zero padding or use something like this:
sample: http://jsfiddle.net/jL4t4/1/
var i, s = "";
for (i = 0; i < 26; i++) {
s += (i === 12) ? "." : Math.floor(Math.random() * 10);
}
Related
This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 6 years ago.
I have this code:
function sellByte() {
if (player.bytes >= 1) {
player.bytes = player.bytes - 1;
player.money = player.money + 0.10;
document.getElementById("bytes").innerHTML = "Bytes: " + player.bytes;
document.getElementById("money").innerHTML = "$" + player.money;
}
}
And whenever I sell a Byte my money value ends up looking like $10.00000003 or something along those lines, how would I go about rounding the money value UP every time this function is run?
Working with float numbers in JS is very tricky. My suggestion is to operate only with smaller units (cents instead of dollars) and then you will only deal with integers and will not have similar issues.
Use Math.round(player.money* 100) / 100 for 2 decimal rounding.
Use any of the following code
Math.round(num * 100) / 100
using fixed Method
var numb = 123.23454;
numb = numb.toFixed(2);
or you can refer following link for more help
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
I want to create a Roth IRA value calculator. The end result would accept values for annual contribution amount, interest rate, and total number of contribution years.
The calculation—a geometric series—that I need is:
Balance(Y) = P(1 + r)Y + c[ ((1 + r)Y + 1 - (1 + r)) / r ]
FWIW, I'm getting my math information here: http://www.moneychimp.com/articles/finworks/fmbasinv.htm
How would one go about writing this in Javascript? I've been reading about the math functions, but I can't seem to wrap my head around it...
I would definitely read up on JavaScripts operator precedence
A few things to note...
Grouping holds the highest precedence (), NOT with square brakets []
square brackets are for accessing object members and array literals.
There is no operator for exponents in JavaScript use Math.pow(x, n)
For mathematical operations, you MUST use operators 4(x + 1) with throw an
error telling you 4 is not a function. 4 * (x + 1) works.
The following operators are evaluated left-right * / % + - with * / %
holding equal precedence over + -. So mathematical operations are going to behave similar to pemdas.
Another note JavaScript is a dynamic loosely typed language. All numbers are 64-bit floating points, which can yield odd results in some math equations, e.g.
> .1 + .2 = 0.30000000000000004
Another good read
For solving any mathematics series below algorithm can be used. Even for some cases it will not satisfy your expected answer, but it will be correct in some other way.
Steps are as below:
1) Get the difference between the numbers as shown below:
2) Keep making difference until it seems same(difference get 0).
3) Put the same last number which is coming same in that sequence and by adding that difference complete the series by coming up.
<pre>
Examples are as below:
1 2 3 4 5 6 **7**
1 1 1 1 1 **1**
1 4 9 16 25 **36**
3 5 7 9 **11**
2 2 2 **2**
1 8 27 64 125 **216**
7 19 37 61 **91**
12 18 24 **30**
6 6 **6**
0 **0**
</pre>
The same above algorithm is implemented in below js code.
<pre>
//the input
var arr=[1,4,9,16];
var pa6inoArrayMelvo = function(arrr){
var nxtArr=[];
for(i=0;i<arrr.length;i++){
if(arrr[i+1] != undefined){
nxtArr.push(arrr[i+1] -arrr[i]);
}
}
return nxtArr;
}
var keepArray=[];
var keepAlltheArray= function(ar){
var tempArr=[];
keepArray.push(ar);
if(ar.length>1){
tempArr=pa6inoArrayMelvo(ar);
keepAlltheArray(tempArr);
}else{
generateArray(keepArray.length-1);
console.log("ans is:"+keepArray[0]);
}
}
var generateArray=function(idx){
if(keepArray[idx+1]){
var a=keepArray[idx+1];
var b=keepArray[idx];
var ans=a[a.length-1]+b[a.length-1];
keepArray[idx].push(ans);
}else{
var ans=keepArray[idx][keepArray[idx].length-1];
keepArray[idx].push(ans);
}
if(idx>0){
generateArray(idx-1);
}
}
keepAlltheArray(arr);
</pre>
As Yann Chabot said
P*(1 + r)*Y + c(((1 + r)*Y + 1 - (1 + r)) / r)
is the right answer but just as a side note, if you dont have P initialy you should set it to 1 by default.
For example, I have a number 123.429. How can I remove the trailing decimals without rounding up to two decimal place.
Hence, I need the number to be up to two d.p. i.e 123.42.
Definitely toFixed() method or Math.round(num * 100) / 100 cannot be used in this situation.
The function you want is Math.floor(x) to remove decimals without rounding up (so floor(4.9) = 4).
var number = Math.floor(num * 100) / 100;
Edit: I want to update my answer because actually, this rounds down with negative numbers:
var Math.floor(-1.456 * 100) / 100;
-1.46
However, since Javascript 6, they have introduced the Math.trunc() function which truncates to an int without rounding, as expected. You can use it the same way as my proposed usage of Math.floor():
var number = Math.trunc(num * 100) / 100;
Alternatively, the parseInt() method proposed by awe works as well, although requires a string allocation.
var number = parseInt('' + (num * 100)) / 100;
You can convert it to a string and then simply truncate the string two places after the decimal, e.g.:
var s = String(123.429);
s.substring(0, s.indexOf('.') + 3); // "123.42"
Please note that there's no guarantee if you convert that final string back into a number that it'll be exactly representable to those two decimal places - computer floating point math doesn't work that way.
another v. cool solution is by using | operator
let num = 123.429 | 0
let num = 123.429 | 0
console.log(num);
let's get the variable name as "num"
var num = 123.429;
num=num*100;
num=num.toString();
num=num.split(".");
num=parseInt(num[0]);
num=num/100;
value of the num variable will be 12.42
Try this
number = parseFloat(number).toFixed(12);
number = number.substring(0, number.indexOf('.') + 3);
return parseFloat(number);
Not the fastest solution but the only one that handles an edge case like 0.0006*10000 = 5.999999999 properly, i.e. if you want to truncate to 4 decimal places and the value is exactly 0.0006, then using Math.trunc(0.0006 * (10 ** 4))/(10 ** 4) gives you 0.0005.
This question already has answers here:
How to deal with floating point number precision in JavaScript?
(47 answers)
Closed 9 years ago.
alert(5.30/0.1);
This gives 52.99999999999999 but should be 53. Can anybody tell how and why?
I want to find that a number is divisible by a given number. Note that one of the number may be a float.
For the same reason that
0.1 * 0.2 //0.020000000000000004
Some decimal numbers can't be represented in IEEE 754, the mathematical representation used by JavaScript. If you want to perform arithmetic with these numbers in your question, it would be better to multiply them until they are whole numbers first, and then divide them.
Scale the numbers to become whole. Then modulus the result.
alert((5.30*10) % (0.1*10));
Now that you have read the article i commented, you should know the root of your problem.
You can partially work around that by scaling you floats...
Then just write a function which:
If its a float
Scale the Numbers
return a boolean representation of the divisibility of the number
function isDivisable(n, d) {
var ndI = 1 + "".indexOf.call(n, "."); //Index of the Number's Dot
var ddI = 1 + "".indexOf.call(d, "."); // Index of the Divisors Dot
if (ndI || ddI) { // IF its a float
var l = Math.max(("" + n).length - ndI, ("" + d).length - ddI); //Longest Decimal Part
var tmpN = (n * Math.pow(10, l)); //scale the float
var tmpD = (d * Math.pow(10, l));
return !~((tmpN % tmpD) - 1); //Substract one of the modulo result, apply a bitwise NOT and cast a boolean.
}
return !~((n % d) - 1); // If it isnt a decimal, return the result
}
console.log(isDivisable(5.30, 0.1));//true
Heres a JSBin
However...
As Integers are stored with 64bit precision, the maximum precision lies about (2^53),
and you will soon exceed the maximum precision when scaling larger numbers.
So it might be a good idea to get some sort of BigInteger Library for javascript
if you want to test floats for divisibility
To find if a number x is divisible by a number y you have to do x % y (modulo). If the result is 0, it is perfectly divisible, any other isn't.
You can get it by following:
var num = (5.30/0.1);
alert(num.toFixed(2));
this will give you 53.00.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you round to 1 decimal place in Javascript?
My Value is 1.450 and I have to round it to 1 decimal place.
I want 1.450 = 1.5 in Javascript can any body fix this please.
You need this:
var mynum = 1.450,
rounded = Math.round(mynum * 10) / 10;
suppose you have
var original=28.453;
Then
var result=Math.round(original*10)/10 //returns 28.5
From http://www.javascriptkit.com/javatutors/round.shtml
You can also see How do you round to 1 decimal place in Javascript?
Given your fiddle, the simplest change would be:
result = sub.toFixed(1) + "M";
to:
result = Math.ceil(sub.toFixed(1)) + "M";
If you use Math.round then you will get 1 for 1.01, and not 1.0.
If you use toFixed you run into rounding issues.
If you want the best of both worlds combine the two:
(Math.round(1.01 * 10) / 10).toFixed(1)
You might want to create a function for this:
function roundedToFixed(_float, _digits){
var rounder = Math.pow(10, _digits);
return (Math.round(_float * rounder) / rounder).toFixed(_digits);
}