AngularJS math joining strings instead of adding - javascript

I have a standard $scope.totals = $scope.totals = {storage:0, dailystorage:0}; and an angular.forEach that adds cam.storage to the $scope.totals.storage to give me the total storage.
I am using this to do that:
$scope.totals.storage = $scope.totals.storage+cam.storage;
The problem is that, say if two cam.storage are 21.09 and 15.82, it'll make $scope.totals.storage 21.0915.82 - basically adding them like strings instead of like math.
How do I make it an addition - not a joining?

Judging from what you've posted (verifying that $scope.totals is already a number), cam.storage is a string. You need to parse it to a number before adding it to the existing value:
$scope.totals.storage += parseFloat(cam.storage);

If they are concatenating instead of adding, it sounds like you need to parse them as decimals (You can also use toFixed(int) to limit the decimals as needed).
$scope.totals.storage = parseFloat($scope.totals.storage)+parseFloat(cam.storage);

My solution I use {{(a*1)+(b*1)}} It work.

Related

How to prioritize sum before string conversion in JavaScript?

Is there a way instead to do like this
"4"+4+3 which will be equal with "443" to somehow do first 4+3 like the result to be "47" (as string)? I have tried in many ways, but no one seems to work. Some ideeas? Thanks.
ps. Not switching numbers
Put the values you want to add in brackets and then concatenate
"4"+(4+3)
Use this
console.log("4"+ (4+3))
const num1=4;
const num2=3
console.log("4"+(num1+num2));
you can use the following code

Print an array(object?) without comma seperator

I am currently writing a large amount of code, but I will keep it simple. I have a javascript array (possibly an object, still unsure exactly of the conventional naming), here is the initialization code:
var myArray = ["assignS" , ";" , "S"]
This is what I get as a console.log() from firebug on the element. There is too much code to post as it is assigned multiple values through many for loops. So this array (or object) is printed later as follows:
document.write("S -> " + myArray);
output:
S -> assignS,;,S
I do not want these commas in the result, it poses problems as some elements in the array may be commas themselves. I have ruled out the .join() method because of this, and am unsure how to proceed.
You ruled out the join method why, exactly? It takes a parameter, the separator, which you can then use to specify no separator:
myArray.join("");
I recommend reading up on the documentation for .join().
Also, I wouldn't recommend you use document.write, it has very few good applications.
The .join method on an array will by default concatenate all items with a comma, but it takes one argument to override this to be any other string to use as the glue - including an empty string.
myArray.join(''); // is "assignS;S"
var a=[1,2,3,4]
var result="";
for(i= a.length-1; i>=0;i--){
result=a[i]+result;
}
document.getElementById("demo").innerHTML=result;
Use this code:
document.write("S -> " + myArray.join(" "));

In JavaScript, is there a way of parsing JSON that turns numbers into strings?

As JavaScript uses floating point maths for all numbers, which does not preserve precision in all cases, I want to parse a JSON object containing numbers but generate strings in the returned JavaScript object rather than number objects. Is there a way to do this using standard or third party libraries?
You can do something like this. This may not be a perfect solution (especially the reg expression), but hope it will help you to solve this.
var json = '{"num1":123.89075576575775676575, "num2":89.5564764646476444844, "num3":56.4353454354353535435435435}';
json = json.replace(/\d+.\d+/g, function(a, b){
return '\"' + a + '\"';
});
console.log($.parseJSON(json )); // I have used jQuery. Any JSON parser can be used
You can try a regexp, something like:
var numstrings = JSON.parse(json.replace(/\:([0-9.]+)(,?)/g,':\"$1\"$2'));
http://jsfiddle.net/rmwcZ/

Javascript string manipulation, combining numbers with strings

I am trying to get values from a data set. My function has to loop from 1 to 7
to get my opening hours for 7 days. what i need to do is:
Where openHours[i] the "i" stands for a number between 1 and 7. I would like to attach that number on the word "openHours" in order to create a new word ex. "openHours1"
What would be the best way to do that? The "alert(i);" is working fine and is generating numbers from 1 to 7. I just need to attach those numbers on the string.
So far i tried everything that can comes in my head but I don't use javascript often so i am kind of stuck.
Thanks for the help.
function hoursFunction()
{
var i =0;
alert("Hello");
for(i=1;i<8;i++)
{
alert(i);
alert(hoursForm.openHours[i].value);
}
}
EDIT: After your comment, it would appear you are trying to get the following variable:
alert(document.getElementById("openHours" + i).value);
However, I would strongly consider using jQuery (or another library) to handle this, and you could do the following:
$("#openHours" + i).val();
You can use the bracket notation to access properties - they're the same thing as indices in JavaScript.
alert(hoursForm[openHours + i].value);

innerHTML in Combination with parseFloat

What I'm attempting to do can be accomplished by the following...
elementContent = document.getElementById('docElement').innerHTML;
elementContent = parseFloat(elementContent);
or even by...
elementContent = parseFloat( document.getElementById('docElement').innerHTML );
but I can't help to wonder if there's a more elegant way to retrieve and assign DOM content as a float that I may be unaware of. Any insight?
There is the unary plus operator which tries to convert a string (or another type's toString()) to a number. It would be used like:
elementContent = +document.getElementById('docElement').innerHTML;
As others have mentioned you can use jQuery as essentially syntactic sugar for .innerHTML here, also.
That's a fine way to go about doing things. The only thing I could suggest would be that if you can avoid working with the HTML markup entirely, by storing the "clean" number as an attribute of the element, that would be preferable, as it would get around problems that might be introduced if the HTML gets fancier than you expect it to be. (For example, sometimes designers want negative numbers formatted with the Unicode "minus" glyph instead of the plain hyphen, because it looks better.)
Thus if you could generate your elements like this:
<span id='docElement' data-value='29.20221'>29.20221</span>
then instead of accessing the value as ".innerHTML" you'd use ".getAttribute()":
var value = document.getElementById('docElement').getAttribute('data-value');
value = parseFloat(value);
Use JQuery:
var html = parseFloat($('#docElement').html());
$('#docElement').html(html);
If you use a library such as jQuery the code for this would be more elegant, like so:
var el = parseFloat( $('#docElement').text() );
Don't forget you might run into an issue where you need to trim() the string as well.

Categories