In my angular.js controller I want to select the array number that matches $routeParams.propertyID by passing it in. The below works:
$scope.selectedProperty = $scope.all_properties[$routeParams.propertyID];
BUT with arrays, 1 = 0, so it selects the previous array that I want. How would I pass in +1 to select the correct array? I have tried the following with no luck:
$scope.selectedProperty = $scope.all_properties[$routeParams.propertyID + 1];
$scope.selectedProperty = $scope.all_properties[($routeParams.propertyID + 1)];
$scope.selectedProperty = $scope.all_properties[($routeParams.propertyID) + 1];
Cheers
You property is probably a string, try add a parse to int before doing math
If you are doing
var calc = "1" + 1 // calc = "11"
If you are not sure, add a console.log($routeParams.propertyID) and check you're firebug console
$scope.selectedProperty = $scope.all_properties[parseInt($routeParams.propertyID,10) + 1];
And if you are reading at pos one instead of pos zero, you should substract
$scope.selectedProperty = $scope.all_properties[parseInt($routeParams.propertyID,10) - 1];
if propertyID is a string, you probably want to convert it to a number for the addition
$scope.selectedProperty = $scope.all_properties[+$routeParams.propertyID + 1];
or, if Brandon's comment is correct
$scope.selectedProperty = $scope.all_properties[+$routeParams.propertyID - 1];
Note in both cases the plus sign (+) before the string that converts it to a number
There are two issues in your context:
First issue: add or subtract
Why are you adding one? Shouldn't you be subtracting one?
If array's zero corresponds to ID's one, then you must do "minus one":
+$routeParams.propertyID - 1
Second issue: string or number
String or number?
Maybe your ID is a string while the array index is a number. In this case, this should work:
$scope.selectedProperty = $scope.all_properties[+$routeParams.propertyID - 1];
But, if you say your first code works, perhaps you don't have an "array", but a hash (or "dictionary").
In this case, after adding or subtracting one, you must convert the result back to string:
$scope.selectedProperty = $scope.all_properties[(+$routeParams.propertyID - 1) + ""];
Related
I am working with a javascript program that needs to be formatted a certain way. Basically, I need to have each section of information from an array be a set length, for example 12 characters long, and no more than that.
The problem I am running into comes when a value in the array is NOT 12 characters long. If I have a value that is less than the 12 characters the remaining character allotment needs to be filled with blank spaces.
The length of each section of information varies in size and is not always 12. How can I add X number of blank spaces, should the length not meet the maximum requirement, for each section?
This is where I am at with adding space:
str = str + new Array(str.length).join(' ');
I am pretty sure what I have above is wrong but I believe I am on the right track with the .join function. Any ideas?
EDIT: I was asked to show a wanted outcome. It is a bit complicated because this javascript is being run out of a web report tool and not out of something like Visual Studio so its not traditional JS.
The outcome expected should look something like:
Sample Image
So as shown above the data is in one line, cutting off longer strings of information or filling in blank spaces if its too short for the "column" to keep that nice even look.
try this code and leverage the wonders of the map function:
let say your array is:
var myArr = ["123456789012", "12345678901", "123"];
now just apply this function
myArr.map(function(item){ //evalueate each item inside the array
var strLength = item.length; //apply this function to each item
if (strLength < 12){
return item + ' '.repeat(12-item.length) //add the extra spaces as needed
} else {
return item; // return the item because it's length is 12 or +
}
})
What you are looking for is the ' '.repeat(x) - where x is the times you want to repeat the string you have set, it could be '*'.repeat(2) and you would get '**', if you want to understand more about it look at the docs
depending on which version of javascript, this might work:
if (str.length < 12) str += ' '.repeat(12 - str.length);
Not exactly sure how you're setup -- but something like the following will accept an array and return another array with all its values being 12 characters in length.
var array = ['Test', 'Testing', 'Tested', 'This is not a Test'];
var adjustedArray = correctLength(array, 12);
function correctLength(array, length) {
array.map(function(v, i) {
if (array[i].length < length) {
array[i] += Array((length+1) - array[i].length).join('_');
}
// might not need this if values are already no greater than 12
array[i] = array[i].substring(0, length);
});
return array;
}
console.log(adjustedArray);
This question already has an answer here:
Function sum not working properly javascript [duplicate]
(1 answer)
Closed 7 years ago.
I'm trying to redirect from www.domain1.com to www.domain2.com getting the actual domain name.
Let's say that our page is www.domain1.com:
var domainName = window.location.host;
var domainNumber = domainName.substr(10, 1);
var finalDomain = (domainNumber+1);
If I print finalDomain on the screen, I got 11. So because of that my redirect is not working.
How do I do domainNumber plus 1, so I got 2 and not 11?
substr method will return you a string, not a number. so you are getting "1" , not 1
when you do "1"+1, you will get "11"
use parseInt() method to convert "1" to 1 before the addition operation.
var finalDomain = parseInt(domainNumber)+1;
domainNumber is a string, not a number, so when you add 1, you're actually concatenating the string "1" onto the end of a string "1" to make "11". You need to convert it into a number using the parseInt() function, as follows:
var domainNumber = parseInt(domainName.substr(10, 1), 10);
Note: The second parameter passed to parseInt() signifies that the string is in decimal (base 10). Now domainNumber is a number rather than a string, so if you try to add one to it you'll get 2.
var finalDomain will be a number, unless you set it to be a string by calling toString():
var finalDomain = (domainNumber + 1).toString() - If you do this, finalDomain will be a string containing the value "2".
Hope this helps.
This function should do the trick parseInt:
Converts a string to an integer.
var finalDomain = parseInt(domainNumber) + 1;
The issue you are having is because in javascript "1" + 1 is "11". So, you need to convert the string "1" to int in order to add it 1 afterwards.
Test it yourself here:
alert("1" + 1 === "11")
alert(1 + 1 === 2)
try this
var domainName = window.location.host;
var domainNumber = domainName.substr(10, 1);
domainNumber = parseInt(domainNumber);
var finalDomain = (domainNumber+1);
u need to parse ur domainNumber variable to integer type in order to do addition.
see here http://www.w3schools.com/jsref/jsref_parseint.asp
document.getElementById("t3").value = document.getElementById("t1").value +
document.getElementById("t2");
Through above code I could not get the result of addition of two numbers.
If you want to add those to values, you have to convert them to integer at first. .value always holds a string.
parseInt(document.getElementById("t1").value, 10) + parseInt(document.getElementById("t2").value, 10);
You are not actually adding two numbers together. You are attempting to add document.getElementById("t1").value (which is a string containing with numbers in it) to document.getElementById("t2"), which is a DOM element.
You probably get a result like this:
43[object HTMLInputElement]
You need to (a) get the value property of the second element and (b) add them together as numbers, rather than as strings.
document.getElementById("t3").value = (+document.getElementById("t1").value) +
(+document.getElementById("t2").value);
(+document.getElementById("t1").value) converts the value into a number. It is the unary plus + operator.
Try this:
document.getElementById("t3").value = parseInt(document.getElementById("t1").value,10) +
parseInt(document.getElementById("t2").value,10);
This is cheeky, but on the off-chance the t3 element that the OP is trying to update is a div or span rather than an input :)
var t1, t2, t3;
t1 = document.getElementById("t1");
t2 = document.getElementById("t2");
t3 = document.getElementById("t3");
t3.innerHTML = parseInt(t1.value, 10) + parseInt(t2.value, 10);
Or
t3.innerHTML = +t1.value + +t2.value;
Lets say I have an amount in string format like this:
amount = '12,000.00'
I want to convert it into a Number (Javascript) or a float.
parseFloat(amount) // this gives me 12 as a result
Number(amount) // this gives me NaN as a result
Other solution I thought was this:
parseFloat(amount.replace(/[,]/g, ''))
This works fine. But the problem here is the Locale.
This would fail when the amount is € 12000,00.
Here ',' has altogether a different meaning.
I looked around for a good solution but couldn't. I am looking for a generalized solution.
This is not that easy, as you can't exactly know what's the delimiter for thousands and what for the decimal part
Consider "12.000.000" is it 12000.000 === 12000 or 12000000?
But if you would set the requirement that the last delimiter is always the decimal delimiter -
meaning if at least one delimiter is given, the last one has to be the decimal delimiter, *if the digits following, don't exceed a defined length.
Then you could try the following
Edit
(see the revs if you're interested in the old function)
I put in the ability to define the max length of digits after the last delimiter "," or "." up until it is treated as float, after that its returned as integer
var amounts = ["12000","12.000,00", "12,000.00", "12,000,01", "12.000.02", "12,000,001"];
formatMoney.maxDecLength = 3; //Set to Infinity o.s. to disable it
function formatMoney(a) {
var nums = a.split(/[,\.]/);
var ret = [nums.slice(0, nums.length - 1).join("")];
if (nums.length < 2) return +nums[0];
ret.push(nums[nums.length - 1]);
return +(ret.join(nums[nums.length - 1].length < formatMoney.maxDecLength ? "." : ""));
}
for ( var i=0,j;j=amounts[i];i++)
console.log (j + " -> " +formatMoney(j));
Gives the output:
"12000 -> 12000"
"12.000,00 -> 12000"
"12,000.00 -> 12000"
"12,000,01 -> 12000.01"
"12.000.02 -> 12000.02"
"12,000,001 -> 12000001" //as you can see after the last "," there are 3 digits and its treated as integer
Another JSBin
You can get the local decimal delimiter in this manner:
1.1.toLocaleString().substr(1,1)
Before parse float, you could make sure the string contains nothing but numbers, possibly a minus sign, and the local decimal delimiter.
The truth is, you'll never know the format. 12,345. Is that 12345, or another locale version if 12.345?
However, if you have consistent decimals, then you'd be able to use the lastIndexOf function on a comma and a period will reveal the decimal position and character.
var price = '12,345.67';
var lastPeriod = price.lastIndexOf('.');
var lastComma = price.lastIndexOf(',');
if (lastComma != -1 && lastComma > lastPeriod) {
decimalCharacter = ',';
} else {
decimalCharacter = '.';
}
console.log(decimalCharacter); //. or , based on how the price string looks - see below
If price is 12,345.67, decimalCharacter will be .. If it's 12.345,67, it'll be returned as ,.
How would it be a nice way of handling this?
I already thought on removing the comma and then parsing to float.
Do you know a better/cleaner way?
Thanks
parseFloat( theString.replace(/,/g,'') );
I don't know why no one has suggested this expression-
parseFloat( theString.replace(/[^\d\.]/g,'') );
Removes any non-numeric characters except for periods. You don't need custom functions/loops for this either, that's just overkill.
Nope. Remove the comma.
You can use the string replace method, but not in a one liner as a regexp allows.
while(str.indexOf(',')!=-1)str= str.replace(',','');
parseFloat(str);
Or to make a single expression without a regexp=
return parseFloat(str.split(',').join(''));
I'd use the regexp.
I don't have enough reputation to add a comment, but for anyone wondering on the performance for regex vs split/join, here's a quick fiddle: https://jsfiddle.net/uh3mmgru/
var test = "1,123,214.19";
var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
var a = parseFloat(test.replace(/,/g,''));
}
var t1 = performance.now();
document.write('Regex took: ' + (t1 - t0) + ' ms');
document.write('<br>')
var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
var b = parseFloat(test.split(',').join(''));
}
var t1 = performance.now();
document.write('Split/join took: ' + (t1 - t0) + ' ms');
The results I get are (for 1 million loops each):
Regex: 263.335 ms
Split/join: 1035.875 ms
So I think its safe to say that regex is the way to go in this scenario
Building on the idea from #kennebec, if you want to make sure that the commas are correct, and you don't want to replace commas, you could try something like this:
function myParse(num) {
var n2 = num.split(",")
out = 0
for(var i = 0; i < n2.length; i++) {
out *= 1000;
out += parseFloat(n2[i])
}
return out
}
alert(myParse("1,432,85"));
// Returns 1432085, as the comma is misplaced.
It may not be as fast, but you wanted alternatives :)
What about a simple function to solve most of the common problems?
function getValue(obj) {
Value = parseFloat( $(obj).val().replace(/,/g,'') ).toFixed(2);
return +Value;
}
The above function gets values from fields (using jQuery) assuming the entered values are numeric (I rather validate fields while user is entering data, so I know for sure field content is numeric).
In case of floating point values, if well formatted in the field, the function will return a float point value correctly.
This function is far from complete, but it quickly fix the "," (comma) issue for values entered as 1,234.56 or 1,234,567. It will return valid number as far the content is numeric.
The + (plus) sign in front of the variable Value in the return command is a "dirty trick" used in JavaScript to assure the variable content returned will be numeric.
it is easy to modify the function to other purposes, such as (for instance), convert strings to numeric values taking care of the "," (comma) issue:
function parseValue(str) {
Value = parseFloat( str.replace(/,/g,'') ).toFixed(2);
return +Value;
}
Both operations can even be combined in one function. I.e.:
function parseNumber(item,isField=false) {
Value = (isField) ? parseFloat( $(item).val().replace(/,/g,'') ).toFixed(2) : parseFloat( item.replace(/,/g,'') ).toFixed(2)
return +Value;
}
In such case, if function is called result = parseNumber('12,092.98'); it will parse the value as it is a String. But if called as result = parseNumber('#MyField', true); it will try to obtain the value from '#MyField'.
As I said before, such functions are far from complete, and can be expanded in many ways. One idea is to check the first character of the given parameter (string) and decide based on the string format where to obtain the value to be parsed (if 1st character is = '#' then it is an ID from a DOM object, otherwise, if it begins with a number, it must be a string to be parsed).
Try it... Happy coding.