Using the following code I want to move a line with id='seekline' by var1 (less than .1 in most cases), but I run into trouble adding var1 and j.
The plus sign concatenates instead of adding. I have tried using Number(), parseInt(), parseFloat(), and forcing addition by multiplying by 1 or adding by 0. For some reason I cannot stop the concatenation. When I use parseInt() or parseFloat() (e.g. parseInt(j,10)) the code stops working.
The string split is to remove the px from element.style.left.
function move(var1) {
element = document.getElementById('seekline');
console.log(var1, element.style.left);
var str=(element.style.left);
var n=str.split("p");
var j = n[0];
Number(j);
Number(var1);
var k = var1 + j;
var f = k.concat("px");
console.log(j, k, f);
element.style.left = f;
}
You need to assign the result of the call to Number(), as it returns the numeric value of the string passed instead of modifying the variable itself.
Note that +foo is the same as doing Number(foo).
function move(var1) {
var style = document.getElementById('seekline').style;
// removes last two 'px' characters
var oldValue = +style.left.slice(0, -2);
// converts to number type, then adds 2 to it
var1 = +var1;
var1 += 2;
// check to see if number is NaN or +/-Infinity
if (isFinite(var1)) {
// only now string concatenates the term 'px' to it
element.style.left = oldValue + var1 + 'px';
}
}
function move(var1) {
var element = document.getElementById('seekline'),
left = parseInt(element.style.left.replace('px',''),10);
element.style.left = ((left++) + var1) + 'px';
}
The secret for you to work with numbers obtained from JavaScript, is to remove the string 'px' and convert them to numbers:
parseInt(element.style.left.replace('px', ''))
Related
I am trying to first get the value of the order property of an element, and then adding 1 to it when I click a button. Thing is, instead of getting 1 and adding 1 and getting 2, I get 11. Shouldn't the "+=" operator add the values? What am I doing wrong?
carouselPrev.addEventListener("click", function(){
const firstPost = document.querySelector(".blog-post");
let firstPostOrder = firstPost.style.getPropertyValue('order');
firstPost.style.order = firstPostOrder += 1;
});
Css properties are strings, and '1' + 1 = 11.
Add "+" before firstPostOrder to convert it to a number.
firstPost.style.order = +firstPostOrder += 1;
the values are strings so they are be concatenated, try parsing to an integer before using parseInt()
Try this
carouselPrev.addEventListener("click", function(){
const firstPost = document.querySelector(".blog-post");
let firstPostOrder = firstPost.style.getPropertyValue('order');
firstPost.style.order = parseInt(firstPostOrder,10) +1;
});
No, the "+=" operator is an assignment operator you'd use in lieu of "=".
let x = 42;
x += 1;
is equivalent to
let x = 42;
x = x + 1;
You want to use just the "+" to add the values, not the "+=".
So i made a function that calculate the price by multiplication how many meters i put the problem is when ever i put decimal numbers it ignores it
heres my script
<script>
function getFillingPrice() {
cake_prices = document.getElementById('price').value;
filling_prices = document.getElementById('test2').value;
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
return t*x;
}
function calculateTotal() {
var total = getFillingPrice();
var totalEl = document.getElementById('totalPrice');
document.getElementById('test3').value =total + " دينار ";
totalEl.style.display = 'block';
}
</script>
You're converting the values to integers when you get them from the DOM.
Change this...
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
to this...
var t=parseFloat(filling_prices);
var x=parseFloat(cake_prices);
Beside the parsing problem, you could use
an unary plus + and
a default value for non parsable value, like letters or an empty string (falsy values) with a logical OR ||.
cake_price = +document.getElementById('price').value || 0
// ^ unary plus for converting to numbner
// ^^^ default value for falsy values
Together
function getFillingPrice() {
var cake_price = +document.getElementById('price').value || 0,
filling_price = +document.getElementById('test2').value || 0;
return cake_price * filling_price;
}
I'm currently struggling with getting the below calcRatio function calculate properly. This is probably basic maths!
The below function works as expected:
function calcRatio(){
var r = frontRing.value/backCog.value;
return r;
}
e.g. frontRing = 52, backCog = 11 r=4.7272....
The below gives me the wrong result:
function calcRatio(){
var r = frontRing.value/(backCog.value + 5);
return r;
}
e.g. frontRing = 52, backCog = 11 r=0.4521.
I ultimately want the 5 to be swapped with an argument.
I am also unable to set the frontRing and backCog variable as .value's without doing it within the function. Could this be causing the issue?
Codepen link
When you expect the extracted value to be a string and have additional computations, it is preferred you use either
parseInt( value , 10) - for integers
parseFloat( value ) - for decimals
In the use case var r = frontRing.value/(backCog.value + 5);
backCog.value is a string since it it a value of input element. When you use + to add a number, it performs a concatenation instead of addition.
var backCogValue = backCog.value; // "11";
"11" + 5 --> 115 and not 16 as you expected.
So the right way to write this piece of code is to use either of the above methods before you want to add a number.
var frontRingValue = parseFloat(frontRing.value);
var backCogValue = parseFloat(backCog.value);
var r = (frontRingValue/ (backCogValue + 5)).toFixed(4);
toFixed is use to format into the number of decimal points that you are expecting.
If 5 is the argument that is passed to the function, then your code will look like
function calcRatio(param) {
var frontRingValue = parseFloat(frontRing.value);
var backCogValue = parseFloat(backCog.value);
var paramValue = parseFloat(paramValue);
var r = (frontRingValue/ (backCogValue + paramValue)).toFixed(4);
}
How can I construct a float value from two whole values?
var amountBeforeComma = 5;
var amountAfterComma = 234;
var amount = ?? //amount == 5.234
There's the math way, using logarithms:
var amountBeforeComma = 5;
var amountAfterComma = 234;
var amount = amountBeforeComma +
amountAfterComma * Math.pow(10, -(Math.floor(Math.log10(amountAfterComma)) + 1));
console.log(amount);
Math.log10(amountAfterComma) gives us the common logarithm of amountAfterComma, then Math.floor(...) on that gives us the characteristic of it (2 in your example), which is (as the linked Wikipedia page puts it) "how many places the decimal point must be moved so that it is just to the right of the first significant digit". Then we add one to that and make it a negative (e.g., -3 in your example) and raise raise 10 to that power to get a value to multiply it by (0.001 in your example) to put it where it should go. Add the amountBeforeComma and we're done.
Or the string then parse way:
var amountBeforeComma = 5;
var amountAfterComma = 234;
var amount = parseFloat(amountBeforeComma + "." + amountAfterComma);
console.log(amount);
(Or use +(amountBeforeComma + "." + amountAfterComma) to convert with implicit coercion rather than explicit parsing.)
Since no one mentioned... There's the JavaScript way:
var num = +(amountBeforeComma + "." + amountAfterComma);
You can make it by casting numbers to strings and then parsing it as float.
var amount = parseFloat(amountBeforeComma + '.' + amountAfterComma);
I have 2 numbers
a = 1548764548675465486;
b = 4535154875433545787;
when I sum these number they are rounded to
a => 1548764548675465500
b => 4535154875433545700
and a + b returns 6083919424109011000 while it should return 6083919424109011273
is there a javascript solution to solve this problem witout the use of a library ?
To work around the precision limitations associated with JavaScript's numbers, you will need to use a BigInteger library like the popular one offered here: http://silentmatt.com/biginteger/
Usage:
var a = BigInteger("1548764548675465486");
var b = BigInteger("4535154875433545787");
var c = a.add(b);
alert(a.toString() + ' + ' + b.toString() + ' = ' + c.toString());
// Alerts "1548764548675465486 + 4535154875433545787 = 6083919424109011273"
Demo: http://jsfiddle.net/69AEg/1/
There are no integers in Javascript, all numbers are double precision floating point.
That gives you a precision of around 15-16 digits, which is what you are seeing.
as per this question
and potential solution i.e. use a library
Personally, I would not use javascript, never been great at numbers. Just try typing 0.1 + 0.2 into any browsers console window. Result is 0.30000000000000004.
Send the calculation to your server side language (as a string) and do the work there, you should have a better outcome.
Technical article on the nuances of floating point numbers here, if you interested
Well, here is a solution I found witout the use of any external library, all I need to do is to define a class that had a property value wich should be a string, and define the function plus
function LongNumber()
{
// it takes the argument and remove first zeros
this.value = arguments[0].toString();
while(this.value[0]==="0")
this.value = this.value.substr(1);
// this function adds the numbers as string to another string and returns result as LongNumber
this.plus = function (Num)
{
var num1 = pad(Num.value.length, this.value);
var num2 = pad(this.value.length, Num.value);
var numIndex = num1.length;
var rest = 0;
var resultString = "";
while (numIndex)
{
var number1 = parseInt(num1[(numIndex)-1]);
var number2 = parseInt(num2[(numIndex--)-1]);
var addition = (number1+number2+rest)%10;
rest = parseInt((number1+number2+rest)/10);
resultString = addition.toString() + resultString;
}
return new LongNumber((rest?rest.toString():"") + resultString);
}
function pad(width, string)
{
return (width <= string.length) ? string : pad(width, '0' + string)
}
}
All i need to do now is to declare 2 LongNombers and use the function plus
var Number1 = new LongNumber("1548764548675465486");
var Number2 = new LongNumber("4535154875433545787");
var Result = Number1.plus(Number2);
Result.value // returns "6083919424109011273"