Unexpected result (NaN) when using parenthesis in a Javascript calculation - javascript

I am trying to do a very simple calculation of 11.000 + 5.000 expecting to have 16.000 then dividing it by 2 expecting to get a final result of 8.000. It was working ok in another language (ahk) but I'm having unexpected results trying it in javascript (Not a Number, 5.5 and 5.50025)
How should I write this calculation to get the expected result of 8.000?
var A = "11.000";
var B = "5.000";
//1st try
var resultA = (A + B) / 2;
alert(resultA);
//2nd try
var resultB = parseInt(A + B) / 2;
alert(resultB);
//3nd try
var resultC = parseFloat(A + B) / 2;
alert(resultC);
//expected = 8.000

Here A + B is doing actually string concationation not simple addition. you need to change them to number first
var A = "11.000";
var B = "5.000";
var resultA = ((+A) + (+B)) / 2;
console.log(resultA);
// You can use toFixed if you three decimal digit
console.log(resultA.toFixed(3));

Here A and B are in string format and Once you do A + B the result will be "11.000" + "5.000" = "11.0005.000" (string concatenation). So to get expected result you should parse each string value to Float/Int then do the addition operation.
Try, var resultD = (parseFloat(A) + parseFloat(B)) /2

Just remove the quotation marks and the vars will be recognized as number not as string so you'll get the expected result.
var A = 11.000;
var B = 5.000;
//1st try
var resultA = (A + B) / 2;
alert(resultA);
//2nd try
var resultB = parseInt(A + B) / 2;
alert(resultB);
//3nd try
var resultC = parseFloat(A + B) / 2;
alert(resultC);
//expected = 8.000

Related

Changing order of characters in a string using JavaScript

I'm catching the date from a form as a string and pass it to a API-Request-URL.
The date string is in this format: 16022019
But the API accepts a date string only in this format: 20190216.
Basically, in my string, I need to change the position of the first 2 characters with the position of the last 4 characters.
I fixed the issue as follow:
let date = e.target.elements.date.value; // 16022019
const dateFirst = date.slice(0, 2);
const dateMiddle = date.slice(2, 4);
const dateLast = date.slice(4, 8);
date = `${dateLast}${dateMiddle}${dateFirst}`; // 20190216
But I'm not sure if this is a good solution. Is there any better way to achieve the same result?
I don't see any problem with your method. in case you want to know alternate you can try this.
This uses regex to capture digits of desired width and than places to desired place.
let str = `16022019`
console.log(str.replace(/(\d{2})(\d{2})(\d{4})/,"$3$2$1"))
You can also use destructuring assignment and rest parameter syntax to do it.
const str = `16022019`;
[d, d1, m, m1, ...year] = str.split("");
const dateStr = [...year,m,m1,d,d1].join("");
console.log(dateStr);
How about mapping the positions:
[/*y*/ 4, 6, /*m*/ 2, /*d*/ 0].reduce((acc, p) => acc + date.slice(p, p + 2), "")
You could also do something like this by using Array#reverse and Array#join.
const data = "16022019"
const res = data.split(/(\d{2})(\d{2})(\d{4})/).reverse().join("");
console.log(res);
using substring
var a = '16022019';
console.log(a.substring(a.length - 4, a.length) + a.substring(2, 4) + a.substring(0, 2))
using substr
var a = '16022019';
console.log(a.substr(a.length-4,4)+a.substr(2,2)+a.substr(0,2))
Here is a way working with dates:
function yyyymmdd() {
var x = new Date();
var y = x.getFullYear().toString();
var m = (x.getMonth() + 1).toString();
var d = x.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
var yyyymmdd = y + m + d;
return yyyymmdd;
}
console.log(yyyymmdd("16022019")) // outputs 20190216
References: https://codereview.stackexchange.com/q/184459

js split only until first given char

I got the following String
var intNote = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work note internal"
which I manipulate the following way:
var tempArr = intNote.split('-');
var tempArr2 = tempArr[1].split('(Work notes)');
internalDate = tempArr[0]; // >> 08.03.2018 09:53:37
internalName = tempArr2[0]; // >> Mustermann, Max
internalNote = tempArr2[1]; // >> Work note internal
When I, for example, have the following String
var intNote = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work
note - internal"
I get the result
internalNote = tempArr2[1]; // >> Work note
I know the 'problem' is the operator .split('-'). How can I define it to split only at the first given "-" that my result will be
internalNote = tempArr2[1]; // >> Work note - internal
Or you could use regex all the way.
/([^-]*)-(.*)\(Work notes\)(.*)/
will give you three capture groups (no. 1-3) with the strings you're after.
var intNote1 = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work note internal",
intNote2 = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work note - internal",
re = /([^-]*)-(.*)\(Work notes\)(.*)/,
arr;
arr=re.exec(intNote1);
arr.shift(); // Remove index 0 (full match)
document.write('<br/>1:' + intNote1 + '<br/>' + arr.join('<br/>'));
arr=re.exec(intNote2);
arr.shift(); // Remove index 0 (full match)
document.write('<br/><br/>2:' + intNote2 + '<br/>' + arr.join('<br/>'));
Instead of first split, use substring
var internalDate = intNote.substring( 0, intNote.indexOf( '-' ) );
var tempArr1 = intNote.substring( intNote.indexOf( '-' ) + 1 );
var tempArr2 = tempArr1.split('(Work notes)');
internalDate = tempArr[0]; // >> 08.03.2018 09:53:37
Provide a regex to split.
Check this.
var intNote = "08.03.2018 09:53:37 - Mustermann, Max (Work notes) Work note - internal"
var tempArr = intNote.split(/-(.+)/)
var tempArr2 = tempArr[1].split('(Work notes)');
internalDate = tempArr[0];
internalName = tempArr2[0];
internalNote = tempArr2[1];
console.log(internalDate)
console.log(internalName)
console.log(internalNote)

Sum up html string numbers using javascript

Hello I have a function that returns numbers inside a <p> tag with the following format:
<p class="numbers">123 + 456 + 789</p>
Is there any way I can do another function or something in javascript to sum up all the numbers and store it into a variable?
Thanks!
// Grab the element
const para = document.querySelector('.numbers');
// Convert the text content to an array and
// make the text number values into actual numbers
const numbers = para.textContent.split(' + ').map(Number);
// Use `reduce` to sum the numbers
const total = numbers.reduce((p, c) => p + c);
DEMO
This should do it:
var string = "<p class="numbers">123 + 456 + 789</p>";
var numbers = string.split(">")[1].split("<")[0].split("+");
var i = 0;
var sum = 0;
while(i < numbers.length){
sum += parseInt(numbers[i]);
i += 1;
}
return sum;
You can use Array.prototype.reduce()
var n = document.querySelector(".numbers").textContent;
var nums = n.replace(/\s/g, "").match(/^\d+|[+-]\d+/g);
var res = nums.reduce((a, b) => Number(a) + Number(b));
document.body.innerHTML += `=${res}`;
<p class="numbers">123 + 456 + 789</p>
var x = document.querySelector('.numbers').textContent.split("+").map(Number);
var y = x.reduce(function(add,num){return add+num})
console.log(y);

Regex two string variables

Say I have two string variables:
a = 'LOVE';
b = '....';
How do I use regex (or whatever else is fastest) to combine a + b to make:
c = 'L.O.V.E.';
In my case, both strings are 4 characters long, always, and the second string is not a fixed character, I just made it a dot to make it look clearer on screen.
You can simply loop through the longer string and in each iteration append one character from both strings to your resulting string. I don't think you need any regular expression there:
a = 'LOVE';
b = '....';
var combinedString = '';
var largerLength = Math.max( a.length, b.length );
for( var i = 0; i < largerLength; i++ )
{
combinedString += a.charAt(i) + b.charAt(i);
}//for()
console.log( combinedString );
The above code will work for strings of any length. In case, you know beforehand that both strings are exactly 4 characters long, I think the fastest and most efficient way would be:
a = 'LOVE';
b = '....';
var combinedString = a.charAt[0] + b.charAt[0] + a.charAt[1] + b.charAt[1] + a.charAt[2] + b.charAt[2] + a.charAt[3] + b.charAt[3];
console.log( combinedString );
You could use Array#reduce for it
var a = 'LOVE',
b = '....';
c = a.split('').reduce(function (r, v, i) {
return r + v + b[i];
}, '');
console.log(c);
How to combine a + b via regex:
var a = "LOVE", b = "....";
var result = a.replace(/./g, (match, i) => match + b[i]);
console.log(result);
There is no need of regex for your problem. You can simply do it with the help of for loop
a = 'LOVE';
b = '....';
var result = '';
var length = Math.max( a.length, b.length );
for( var i = 0; i <+ length-1; i++ )
{
result = result + a.charAt(i);
result = result + b.charAt(i);
}
alert("Result of combined string is :"+ result);
You can use array functions on array likes (in this example strings) to iterate over it's items.
var a = 'LOVE',
b = '....',
c = Array.prototype.map
.call(a, (v, i) => v + b[i]).join('');
console.log(c);
If your second string is always composed of dots, instead of repeating same characters in string, try something like this:
Using Delimiter
var a = "LOVE";
var delimeter = ".";
var result = a.split("").join(delimeter) + delimeter;
console.log(result)
Array convert + manual concatenation
As an alternate to string.charAt, you can try something like this:
Note: you should do a1[i] || "" for cases where value can be undefined. Also you should use .toString() to avoid cases where both values are numeric and result will be addition instead of concatenation.
var a = 'LOVE';
var b = '....';
var c = ",,,,,,,,,,,";
function mergeStr(a, b) {
var a1 = a.split("");
var b1 = b.split("");
var len = Math.max(a.length, b.length)
var r = "";
for (var i = 0; i < len; i++) {
r += (a1[i] || "").toString() + (b1[i] || "").toString();
}
return r;
}
console.log(mergeStr(a,b))
console.log(mergeStr(a,c))

jquery adding input val together

For some reason my code returns "0111" when the returned value should be 3 adding the numbers together.
Is there a better way to write this so it adds the value of the input text?
var p = $(".p").val();
var r = $(".r").val();
var d = $(".d").val();
var s = $(".s").val();
var checkability = p + r + d + s;
alert(checkability)
You are concatenating strings you need to cast it to numeric. val() return data as string, or explicitly use parseInt(var, 10) or parseFloat based on your type.
Simple way is t use unary + operator prefixing the variable:
var checkability = +p + +r + +d + +s;
Fiddle
Sure, the easiest thing is to coerce the string values into integers like:
var p = +$(".p").val();
var r = +$(".r").val();
var d = +$(".d").val();
var s = +$(".s").val();
jsFiddle example
You could also use the longer parseInt() function like var p = parseInt( $(".p").val(), 10);
Use parseInt to make them integers
var p = parseInt($(".p").val(),10);
var r = parseInt($(".r").val(),10);
var d = parseInt($(".d").val(),10);
var s = parseInt($(".s").val(),10);
var checkability = p + r + d + s;
alert(checkability)

Categories

Resources