Round a number down in JavaScript - javascript

I know this maybe very simple and common but I want to know about this calculation:
Example: I have a decimal number 4.716981132075472, but I only need the 4 number, is there any calculation able to do this?

Try round off:
var result = 4.716981132075472 << 0;
alert(result);
OR
var result = Math.floor(4.716981132075472);
alert(result);

You are looking for Math.floor() docs here

Try Math.floor( 4.716981132075472);. This rounds the number down to the nearest integer, thus solving your problem.

Related

How to calculate logarithm with base N for big integer?

I'm using this BigInteger.js for some calculations:
let myBigInt = bigInt(20).pow(200) // gets 160693804425899027554196209234116260252220299378279283530137600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
I'd like to apply the logarithm to the big integer but in the docs I could not find any matching function. How can I implement a log(baseN, valueX) function for the BigInteger.js library?
Note: let myLogarithm = myBigInt.log(baseN) is not a valid implementation.
Note: After a lot of try&error I did found a working solution my own and I will post it here because I'm pretty sure there are a few more people then me that also gots faced with the same issue right there. So I hope, I could help :)
Have a look at wikipedia, as I did because theres a very nice article about baseConversion.
Below you can find a function for Math.log(base, value) that is able to calculate the log(base) from a value.
Math.log = (function() {
var log = Math.log;
return function(base, n) {
return log(n)/(base ? log(base) : 1);
};
})();
To calculate the logarithmToBaseN for bigInt-values just use this line of code:
let logarithmToBaseN = (myBigInt.toString().length * Math.log(baseN, 10) + Math.log(baseN, parseFloat("0." + myBigInt))) - 1);
Edit: This soltuion is a tiny workaround bacause parseFloat("0." + myBigInt) converts a big value like 100000 to a really small one like 0.100000,... what causes that it will be in integer precision.
According to #Jonas W's comment: The solution is very accurate for lower bases like (5, 10, ...) combined with low values like 10, 1000, 100000 - but for really big values like bigInt(20).pow(200) is it not.
Note: Using parseFloat (IEEE 754 double precision floating-point) means, you have a maximum of 52 bits of precision, which is a bit more than 15 decimal places. After that - the accuracy will be killed.
Note: For really big values bigInt(20).pow(200) combined with really big Bases like 100*(and more) it seems to be pretty accurate again.
Greetings, jonas.

Math.flooring a scientific notation at a certain decimal

I am trying to Math.floor a scientific notation, but at one point the number gets too big and my current method doesn't work anymore. This is what I am using atm
var nr = (number+"").length - 4;
if( nr > 1 ) {
nr = Math.pow( 10, nr );
number= Math.floor(number/nr)*nr;
number= number.toExponential(3);
}
When it becomes a scientific notation by default, I think that's e20+, than my .length method doesn't work anymore since the length it returns isn't accurate. I can think of a work around, and that's to find out the number after e, and update my nr to Math.floor it properly, but it seems like so much work to do something so simple. Here's an example number 8.420960987929105e+79 I want to turn this into 8.420e+79, is there a way I can Math.floor the third decimal point always, no matter what the number is? As it stands when I use toExponential(3) it always rounds the number. My numbers can get as high as e+200 easily, so I need an easier way of doing what I'm currently doing.
Edit: managed to find a work around that works besides Connor Peet's answer for anyone who wants extra options
var nr = 8.420960987929105e+79+"";
var nr1 = nr.substr(0,4);
var nr2 = nr.substr(4, nr.length);
var finalNr = Number(nr1 + 0 + nr2).toExponential(3);
This way is more of a hack, it adds a 0 after the 4th number so when toExponential rounds it up, it gets 'floored' pretty much.
I wrote a little snippet to round a number to a certain number of significant figures some time ago. You might find it useful
function sigFigs(num, figures) {
var delta = Math.pow(10, Math.ceil(Math.log(num) / Math.log(10)) - figures);
return Math.round(num / delta) * delta;
}
sigFigs(number, 3); // => 8.420e+79

Strip and ignore decimals in javascript

How can I simple delete everything after a decimal place including the decimal so I am left with a whole number?
I.e. 325.6899 needs to be 325 with no rounding.
Ideally I'd like a function that does this but I don't know of any in Javascript.
You can use Math.floor:
var foo = Math.floor(325.689);
console.log(foo); // = 325
you can simply do
parseInt(325.6899);
Another different answer
var foo = 325.689;
console.log(Number(foo.toString().split(".")[0])); // = 325
Fiddle
Here's another;
var result = 325.689 - 325.689 % 1;
Probably not faster than floor nor better but it works.

Make number Value opposite in JavaScript

I want to know if it is possible to make a number the opposite to what it currently is using JavaScript. ie if a number is 400. Is it possible to make it -400, similar if a number is -400 is it possible to make it 400?
This is not jQuery!
Just multiply it by -1.
num = "400"
console.log(-num);
Core JS,
function opposite(number) {
return(-number);
}
As the shorter solution from http://www.codewars.com/
In one Line..
const opposite = number => -number;
function opposite(number) {
let result;
if (!isNaN(Math.sign(number))) {
result = number * (-1);
}
return result;
}
const opposite(num) {
return num * -1;
}
What I also realized was that if you just:
const opposite(num) {
return -num;
}
The negative can be used to create a positive when returning the num because if it is a negative integer turning into a negative number the two negatives cancel each other out into a positive.
To shorten the code you can also use:
const opposite = num => -num;
All ways work. It's all in how fast you want the solution. The faster the better. The most simple way a code can be written the better.
I really liked #KRESH 's answer because it made me find out what Math.sign() was. The whole adventure of figuring out what his code did was fantastic. I wonder what it could be best used for. That's what's going to be fun figuring out next.

Incorrect multiplication answer

I understand that JS math is not perfect. but how can i format this to get the correct answer as I have a cart item which costs .60 cents and they can change the quantity?
var a=3*.6;
document.write(a);
writes 1.7999999999999998
Obviously I want to write 1.8. any ideas how to accomplish this?
Use toFixed to round it back:
var a = 3*.6;
document.write(a.toFixed(2));
If you need it as a number, add a + sign before it:
var a = 3*.6;
console.log(+a.toFixed(2)); // Logs: 1.8, instead of "1.80"
var a=3*.6;
a = Math.round(a*10)/10;
document.write(a);
Since you want to round to the 10ths place, you need to multiply the number by 10, round the result of that multiplication to the nearest whole number, and then divide the result by 10.
It's not sexy, but ya gotta do whatchya gotta do.
var a=(3*(.6*100))/100;
document.write(a);
Example: http://jsfiddle.net/aJTJq/
multiply .6 by 100 to get the 60 cents
multiply that by 3
divide it by 100 to return it as a dollar figure
Write the .6 as a fraction: a=3*6/10 and you get 1.8
As a more general rule, you could try rounding to the nearest millionth with
Math.round(result*1000000)/100000 and seeing what that gets you.
What you want to do is have some type of rounding function.
Try this:
Rounding Function
<script language="javascript" type="text/javascript">
function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes)
}
</script>
And then something like this to call the function
<form name="roundform">
<input type="text" name="numberfield" value="">
<input type="button" value="Round" onClick="roundNumber(numberfield.value, 2);">
</form>
This example just takes a number in the text field and ensures that it is rounded to two decimal places.
This was taken from http://www.mediacollege.com/internet/javascript/number/round.html
There are more examples on this link as well. Hopefully this helps.
Cheers

Categories