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.
Related
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.
I'm working with the very handy, crafty, and cool JS library, NumeralJS
I went into their examples and docs but I couldn't find an answer to something I have in mind, so, I'm posting here hoping to get a quick answer:
basically, if I have a variable, say x, and x can have two types on numbers in it: a whole number, and a number with a decimal point.
say, if x's value is a flat 10, the numeralJS output on HTML should look like "10".
So, when x's value is a 3.67144, the output I wanted will be "3.7".
But here's my dilemma:
When I use something like this,
var x = 10;
return numeral(x).format('0');
// I get "10"... cool
but,
var x = 3.67144;
return numeral(x).format('0');
// I get "4", when I want 3.7 :(
then, I use this,
var x = 10;
return numeral(x).format('0.0');
// I get "10.0"... not what I want :(
and,
var x = 3.67144;
return numeral(x).format('0.0');
// I get "3.7"... which was okay, but you know...
So, yeah. Any ideas, good folks? (Should I involve some complicated conditional ninjutsu on this? Probably?)
... Nevermind...
var x = 3.67144; //or 10
return numeral(x).format('0.[0]');
Worked like a freaky voodoo. I was playing around and stumbled on it.
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.
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.
I have a javascript that calculates the percentage from two fields (retail and network) and then dumps that percentage into another field (markup).
As I am relatively new to the world of JS I have ended up reusing the code for several rows of fields. This goes against DRY and KISS principles so I was wondering if you could give me some input on how to optimise my code so that it can handle any two fields and then dump a value to a third field.
Here is a screenshot of my form segment that is using it.
http://i.imgur.com/FHvDs.png
Here is my code I am using, I have had to reuse it four times and place the code in four functions e.g. (percentage1, percentage2, percentage3, percentage4) each one of these functions deals with a row of fields show in the screenshot.
function percentage1()
{
//the dividee
x = document.getElementById('tariff_data');
//the divider
y = document.getElementById('network_data');
//if the first value is lower than the second, append a "-" sign
if (x.value < y.value)
{
z = "-"+(x.value/y.value)*100;
document.getElementById('markup_data').value = z;
}
//not a negative percentage
else
{
z = (x.value/y.value)*100;
document.getElementById('markup_data').value = z;
}
}
function percentage2()
{
//the dividee
x = document.getElementById('tariff_rental');
//the divider
y = document.getElementById('network_rental');
//if the first value is lower than the second, append a "-" sign
if (x.value < y.value)
{
z = "-"+(x.value/y.value)*100;
document.getElementById('markup_rental').value = z;
}
//not a negative percentage
else
{
z = (x.value/y.value)*100;
document.getElementById('markup_data').value = z;
}
}
etc etc....
These functions are called using the onchange HTML attribute
Also when I divide by a decimal number it gives the wrong value, any Ideas how to make it calculate the correct percentage of a decimal number?
My code also gives out these strange outputs:
NaN , Infinity
Thanks
Rather than optimization, let's focus on correctness first =)
Note that the HTMLInputElement.value property has type "string", so your arithmetic operators are doing implicit type conversion which means you are likely often doing string concatenation instead of the numeric operations you expect.
I strongly recommend explicitly converting them to numbers first and checking for invalid input, also, don't forget to declare your variables first using var so they don't potentially clobber globals, e.g.:
var x = Number(document.getElementById('tariff_data'));
var y = Number(document.getElementById('network_data'));
if (!isFinite(x) || !isFinite(y)) {
// Handle non-numerical input...
}
You can also use the parseFloat function if you prefer, e.g.:
var x = parseFloat(document.getElementById('tariff_data'), 10);
I highly recommend doing some formal learning about the JavaScript language; it is full of pitfalls but if you stick to the "good parts" you can save yourself a lot of hassle and headache.
With regard to DRYing your code out; remember that you can:
Pass parameters to your functions and use those arguments within the function
Return values using the return keyword
In your case, you've got all your multiplication code repeated. While trying to fix the string vs. number problems maerics has already mentioned, you could do something like this:
// We're assuming 'dividee' and 'divider' are numbers.
function calculatePercentage(dividee, divider) {
var result;
// Regardless of the positive/negative result of the calculation,
// get the positive result using Math.abs().
result = Math.abs((dividee.value / divider.value) * 100);
// If the result was going to be negative...
if (dividee.value < divider.value) {
// Convert our result to negative.
result = result * -1;
}
// Return our result.
return result;
}
Then, in your percentage functions, you can just call this code like so:
function percentage1() {
var tariff, network, markup;
tariff = parseFloat(document.getElementById('tariff_data').value, 10);
network = parseFloat(document.getElementById('network_data').value, 10);
markup = document.getElementById('markup_data');
markup.value = calculatePercentage(tariff, network);
}
Obviously, you could take this further, and create a function which takes in the IDs, extracts the values from the elements etc., but you should try and build that yourself based on these tips.
Maerics also makes a very good point which you should take note of; learn more about the Good Parts of JavaScript. Douglas Crockford's book is excellent, and should be read and understood by all JS developers, IMHO.
Hope this helps you clean your code up!