This question already has answers here:
Javascript (+) sign concatenates instead of giving sum of variables
(14 answers)
Closed 6 years ago.
I have been playing around with cookies for the first time, and I have saving part of it completed. The data I'm saving are numbers and the most important part of these nubers is that I can add, subtract and so on with these. However when I try to add a number to one of my saved parametres it adds them as if they were text.
Example:
I have a cookie called value, and when I want this value I use a script I found by Jeffery To that looks like this:
function readCookie(name) {
return (name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1];
}
After I have collected this cookie I want to add one to it. Lets say that value equals nine, when it should look like this: value + 1 = 10. Simple math. However it gives me this 91. Why does it do this? I know that it is because it thinks the numbers are a string of text, but how can I get this to behave like numbers?
Solution
After reading the comments I learned that i needed to put my value inside a parseInt(). So i simply modified the funtion to say:
function readCookie(name) {
return parseInt((name = new RegExp('(?:^|;\\s*)' + ('' + name).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)').exec(document.cookie)) && name[1]);
}
The + operator in JavaScript can mean mathematical addition or string concatenation. The one you get is based on the implicit type of the operands. If one of the operands is a string, the other will be converted to a string and you'll get concatenation.
The trick is to do the math on the numbers first (you can surround the math portion with parenthesis or do the math in a separate statement) and then inject the result into your string.
To force a string containing a number character into a number, you can use parseInt() and parseFloat():
var result = parseInt(value, 10) + 1;
Note that with parseInt(), you should supply the optional second argument, which specifies the radix for the operation. If the first argument happens to refer to a string that contains a hex value, the result will be based on hex, not base 10. That's why 10 is used in my example.
Also note that both parseInt() and parseFloat() stop after finding the first non-valid characters that can't be treated as numbers. So, in a string like this: "Scott7Marcy9", you would get NaN.
Cookies are saved as string values as you guessed. To get your desired effect, you're going to need to parse your value. If you are absolutely sure it will be an integer, use:
parseInt(value) + 1
Related
I am making a base converter that can convert any number in any base to the same number in any other base. Since the bases could be any number the result could have digits that represent a number greater than 10. In order to have only one character correspond to each digit in the final result, I plan to assign Unicode characters to each digit corresponding to a value greater than 10 by using String.fromCharCode(Base 10 number digit represents). However, I noticed that there was a problem with this method; It seems as if a lot of the values are blank when outputted onto the HTML webpage or only output an empty box that looks like this: ⯣. When I tried to see if the value of the Unicode character equaled the empty box or an empty string by using an if statement, it always seemed to return false, even when the Unicode character associated with the digit returned the same empty box. Please may you help me understand why this is, and how I can construct the if statement such that it will work like I want it to?
You could try this:
function convertToDecimal(num, base) {
return window.parseInt(num.toString(), base);
}
const binary = 10;
const base = 2;
console.log("Decimal version:", convertToDecimal(binary, base))
i have a Javascript file that calculates and parse the rows in a crm module called jobs.
I have function called recalculateSummary that calculate the price like this
I want it to show 3,578.00 in total like Line Total
The problem is the function parseFloat i think it ignores the ',' as i want if i write 3,578.00 the total should be 3,578.00.
I was able to achive this by removing parseFloat function and removing the ReplaceAll function but i got error when i add more rows the total value becomes 0.00.
recalculateSummary: function(){
var subtotal = 0;
$.each($('.row_line_total'), function(index,value){
lineTotal = $(value).html().replaceAll(',','.').replaceAll(' ','');
subtotal += parseFloat(lineTotal);
});
i know the question isn't clear but i need some help
Are trying to add toFixed(2) for calculation result?
I mean this:
$('.summary_subtotal').html($.number(subtotal,2));
->
$('.summary_subtotal').html($.number(subtotal.toFixed(2),2));
The reason is that by replacing the comma with the dot, parseFloat will interpret that as the decimal separator and so your number suddenly is a factor of 1000 smaller.
Take for example 3,578.00
Your code will grab that value as a string with $(value).html().
This is OK, although it would be better to do $(value).text() as
you are not really interested in HTML encoding, but plain text.
Then the code performs a disastrous replacement with
.replaceAll(",", "."). This will turn the string to "3.578.00"
(Not good!).
Finally the code converts this string to number with parseFloat.
The first dot is interpreted as decimal separator, not as thousands
separator (which it originally was). The second dot cannot be
interpreted as part of the number, and so parseFloat returns a
number with value 3.578. You probably have some other mechanics in
place to only display 2 decimal digits, so this value ends up on the
page as 3.58 (rounded).
In order to fix this problem, replace this:
lineTotal = $(value).html().replaceAll(',','.').replaceAll(' ','');
with:
lineTotal = $(value).text().replace(/[^.\d]/g, '');
Here we remove anything that is neither a dot (.), nor a digit (\d), using a regular expression: [^.\d]. So now the example value will become "3578.00" (the thousands separator is removed). parseFloat will turn this string into the number 3578. Your rendering mechanics will possibly render that with two decimals and a thousand separator as 3,578.00
All in all it is better to write your logic based on numeric variables and only use the DOM elements for output, not to read values from it (which are already formatted).
This question already has answers here:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 5 years ago.
Why does Javascript give an output of 0 when I use the odd operator?
What is the difference between subtraction and addition with a string?
var x = 1;
console.log(x+'1') // Outputs 11
console.log(x-'1') // Outputs 0 -- but why?
So how can I do mathematical calculations?
The + operator has one of two three meanings in javascript. The first is to add numbers, the second is to concatenate strings. When you do 1 + '1' or '1' + 1 the operator will convert one operand that is not a string to a string first, because one other operand is already evaluated to be a string. The - operator on the other hand has just one purpose, which is to subtract the right operand from the left operand. This is a math operation, and so the JS engine will try to convert both operands to numbers, if they are of any other datatype.
I'm not sure though why typecasting to strings appears to have precedence over typecasting to numbers, but it obviously does.
(It seems to me the most likely that this is a pure specification decision rather than the result of other language mechanics.)
If you want to make sure that the + operator acts as an addition operator, you can explicitly cast values to a number first. Although javascript does not technically distinguish between integers and floats, two functions exist to convert other datatypes to their number equivalents: parseInt() and parseFloat() respectively:
const x = 10;
const result = x + parseInt('1'); // 11
const y = 5;
const result2 = y + parseFloat('1.5'); // 6.5
const result3 = y + parseInt('1.5'); // 6
Edit
As jcaron states in the comment below, the + operator has a third meaning in the form of an unary + operator. If + only has a right operand, it will try to convert its value to a number almost equivalent as how parseFloat does it:
+ '1'; // returns 1
+ '1.5'; // returns 1.5
// In the context of the previous example:
const y = 5;
const result2 = y + +'1.5'; // 6.5
Dhe difference with parseFloat is that parseFloat will create a substring of the source string to the point where that substring would become an invalid numeric, whereas unary + will always take the entire string as its input:
parseFloat('1.5no-longer-valid'); // 1.5
+ '1.5no-longer-valid'; // NaN
That is because + is a concatenation operator. So javascript considers it to be a concatenation operator rather than a mathematical operator.But it is not the case with / ,* ,/ etc.
This happens because + its also used to concatenate strings. Then, JS always will find the better way to make the correct typecasts basing on types. In this case, the x+'1' operation, will be identified as string type + string type.
Otherwise, x-'1', will become int type - int type.
If you want to work with specific types, try to use type cast conversions, link here.
This question already has answers here:
Javascript concatenating numbers, not adding up
(3 answers)
Closed 7 years ago.
var tt = gas+0.1
document.write (vartt);
Duplicate
You could make use of Number function too.
var tt = Number(gas) + 0.1;
document.write(tt);
The user entered a string. If you want to do arithmetic with it instead of string concatenation, you must convert to a number. There are many different ways to do that including parseInt(gas, 10), parseFloat(gas), Number(gas) and +gas:
Here's one implementation:
var tt = parseFloat(gas) + 0.1;
document.write(tt);
Also, your document.write() statement was not correct either. The variable name is just tt, not vartt.
Unless you are using <input type="number" /> for the input, the user provided data will be a string. By default, when you try to add a string + a number it will cast that number to a string. You can do what Видул Петров suggested and add the unary + to gas to force cast it to a number, however if it's still a string that can't be cast to a number (like someone entering in the word 'five' vs '5'), youll get NaN as a result unless you have the proper control over the incoming data.
In JavaScript, can someone explain the results of the 2 following expressions:
"4" + 4 and 4 + "4"
Thanks!
Both will result in the String:
"44"
This is because the + operator serves 2 purposes -- addition and concatenation. And, if either operand is a String (or is cast to a String by the internal ToPrimitive()) they'll be concatenated.
This is described in the specification as:
7) If Type(lprim) is String or Type(rprim) is String, then
a) Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8) Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3.
If you want to ensure addition, you can use parseFloat() or the unary + on each:
var a = "4", b = 4;
console.log(parseFloat(a) + parseFloat(b)); // 8;
console.log((+a) + (+b)); // 8, extra parenthesis for clarity
1+'1'+1 = '111'
1+1+'1' = '21'
'1'+(1+1) = '12'
'1'+1+1 = '111'
Javascript performs math until it hits a string and then switches to concatenation, and it also follows regular formula rules run () operations first.
they'll both be '44'. The presence of the '4' as a string casts the whole operation to a string, so the two characters are concatenated.
Cited from: http://javascript.about.com/od/variablesandoperators/a/vop10.htm
One thing that can be confusing to beginners is that JavaScript uses +
with text strings to mean something completely different from what it
means with numbers. While with numbers + means add the numbers
together with text + means concatenate them together. Concatenation
basically means joining one text string onto the end of the first so
that "my"+"book" gives "mybook" as a result. Where beginners tend to
get confused is that while 3+3 gives 6, "3"+"3" gives "33".
You can also use += with text strings to directly add the variable or
text on the right onto the end of the text string variable on the
left.
Mixing Data Types
Additional confusion can arise when you are working with variables
that are of different types. All operations require that the variables
that they are operating on both be of the same type. Before JavaScript
is able to perform any operations that involve two different data
types, it must first convert one of the variables from one type to the
other. You can't add a number to a text string without first either
converting the number to text or the text to a number.
When converting between data types we have two choices. We can allow
JavaScript to do the conversion for us automatically or we can tell
JavaScript which variable that we want to convert.
JavaScript will attempt to convert any text string into the number
equivalent when performing subtraction, multiplication, division, and
taking remainders. Your text string will actually need to contain
something that JavaScript can convert to a number (i.e., a string like
"10") in order for the conversion to work.
If we use + then this could either mean that we want to convert the
string to a number and add then or that we want to convert the number
to a string and concatenate them. JavaScript can only perform one of
these two alternatives. It always converts numbers to strings (since
that will work whether the string contains a number or not).
Here are some examples.
"5" - 3 = 2;
"5" + 3 = "53"
2 + "7" = "27"
5 + 9 + "1" = "141"
Since subtraction only works with numbers 1 converts the text string
into a number before doing the subtraction.
In 2 and 3 the number is converted to a text string before being
concatenated (joined) to the other text string.
In 4 the leftmost addition is done first. Since these are both numbers
they are actually added together and not treated as text. The result
of this first addition leaves us with a similar situation to the third
example and so the result of that addition is converted to text and
concatenated.
To actually force JavaScript to convert a text string to a number we
can use Number("3") or alternatively to force JavaScript to convert a
number to a text string we can use String(5).
Expressions in JS work on two prime principles.
B O D M A(includes concat) S
Left to right order of execution
However, its not straight forward
for + operator
as far as it encounters numbers it will do math addition using left to right execution, However,as soon as it encounters a string, it concatenates the result (that's calculated till encountering a string) with rest of the expression.
//left to right execution
console.log(10+10+"10") //2010, (10+10) of numtype + "10" of stringtype concat(20+"10")
console.log(10+10+"10"+10+10) //20101010,
//(10+10) of number type + "10" stringtype(now since a string is enc.) + (10+10) of number type would act as strings and get concatenated = 20+"10"+"1010"
console.log("10"+[10,10,10]+10) //1010,10,1010
//"10"of stringtype + array of numtypes + 10 of numtype
// "10" concats with first element of array, last number 10 concats with last element of array.
for all other operators such as -,*,/,^...
if all occurrences are numbers/numbers as string, it will do the respective math operation treating "numbers as string" to be numbers.
console.log("10"-10) //0
console.log("10"/10) //1
console.log("10"*10) //100
console.log(10+"10"*10) //110 //BODMAS
console.log(Math.pow(10,"10")) //10000000000
if there are occurrences of non-numeric strings,arrays,objects in the middle of expression that involve (-,*,/,^...)math operations, it will always return NaN
console.log(10-{id:1,name:"hey"}-10) //NaN
console.log(10-10-"hey"-10-10-10) //NaN
console.log("hey"/10) //NaN
console.log("hey"* 3) //NaN
console.log(["hey","hey"]*"3") //NaN
console.log("10"/[10,10,10]/10) //NaN