I'm using jQuery to get the CSS transform property:
this.$slider.css('transform')
The following returns:
translate(100px, 0px)
How would I get just the number 100 as a variable using javascript or jQuery?
With javascript string functions:
str = this.$slider.css('transform');
a = str.substring(str.indexOf('(')+1,str.indexOf('px'));
alert(a); //100
you can use regex:
'translate(100px, 0px)'.match(/[^\(]+\(([0-9]+)/)[1]
var transform = this.$slider.css('transform'),
first = transform.split('(')[1].split('px')[0];
a small regex would suffice to just pull the first number, but note this isn't picky that they are pixel units or anything else that might come back in the CSS
this.$slider.css('transform').match(/\d+/)
s = "translate(100px,0px)"
parseInt(s.substring(s.indexOf("(")+1), 10) // returns 100
Just take a slice starting at index 10, and send it through parseInt.
var str = this.$slider.css('transform');
var n = parseInt( str.slice(10), 10 );
Or if there will be other types of results than transform, you can do this:
var n = parseInt( str.split("(")[1], 10);
Related
Good morning / Afternoon / evening :).
i have two integers that i want to turn them floats, with 4 decimal numbers to use them on GPS coordinates:
var z = y.toFixed(4);
var p = x.toFixed(4);
But there are a situation that is bugging me, that is the sum between these 'z' and 'p':
var t = z + p;
After this instruction, i want to print the result on the screen with some common functions like:
document.write(z); document.write("<br />");
document.write(t);
document.write("<br />");
document.write("<br />");
The result that i get is:
0.0000
0.0000300.0000
1.0000
1.0000300.0000
2.0000
2.0000300.0000
But what i really want is:
300.0000
301.0000
302.0000
How can i sum 'z' and 'p', after all? :S
Noob question, i know :S.
Kind regards,
Sam
That's because .toFixed() returns a String object rather than a Number, so the + operator performs concatenation.
Instead you should perform the addition of the actual numbers first and then perform .toFixed() to "round" the result for display.
var t = (x + y).toFixed(4);
document.write(t);
I think what you want is :
var t = x + y;
var p = t.toFixed(4);
document.write(p);
try this
var t = (x + y).toFixed(4);
fiddle here
The JavaScript method toFixed converts your number into a string. Thus, when you perform operation z + p it actually is string concantenation and not addition of numbers. You may first add your numbers and afterwards apply toFixed.
toFixed() returns a string, which means you are concating string when you use var t = z + p. You need to first sum your coordinates and then call toFixed().
How much is p? Are you concatenating strings?
Try with var t = parseFloat(z) + parseFloat(p);
I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50. How would I do that? The offending code looks like this.
$('#selectform').val() *50);
If I use
$('#selectform').val() +1 *50);
The result is not correct.
Parentheses should be used.
($('#selectform').val()*1 + 1) *50;
Your current expression is interpreted as:
var something = $('#selectform').val();
var another = 1 * 50;
var result = something + another
The *1 after .val() is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:
var something = $('#selectform').val() + "1"; //String operation
var result = something * 50; // something is converted to a number, and
// multiplied by 50
Correct parentheses and use parseInt function -
(parseInt($('#selectform').val(),10) +1) *50;
The data from $('#selectform').val() is probably being treated as a string.
Use parseInt($('#selectform').val()) to convert it to an int before the multiply.
You should have a look at the operator precedence in JavaScript.
You need to force the addition to happen before the multiplication with parentheses:
bar myVal = ($("#selectform").val() + 1) * 50;
Using toFixed like follows gives:
var a=0.5, b=1, c=1.5;
console.log(a.toFixed(), b.toFixed(), c.toFixed());
// 0.5 1.0 1.5
However, when it's a whole number, I only want it to return "1".
Help!
You could use a Regular Expression to remove a trailing .0, if it exists:
Number.prototype.safe_toFixed = function (x) {
var that = this.toFixed(x);
return that.replace(/\.0$/, '');
}
This is what I did and it works every time.
var x= Number(54.03).toFixed(1);
if(Math.floor(x) == x) {
x = Math.floor(x);
}
alert( x );
I am just comparing the two types to see if they match. If they do, then I know there may or may not be an extra zero. Either way, I simply round up (ceil) or down (floor) and get the whole number with no annoying decimal and trailing zero.
You could use split() and a if condition:
var digit = 1.2
var ret = digit.toFixed(1);
var intValue = ret.split('.');
if(intValue[1] == 0){
digit = intValue[0];
}
When I want to select the nth character, I use the charAt() method, but what's the equivalent I can use when dealing with integers instead of string values?
Use String():
var number = 132943154134;
// convert number to a string, then extract the first digit
var one = String(number).charAt(0);
// convert the first digit back to an integer
var one_as_number = Number(one);
It's a stupid solution but seems to work without converting to string.
var number = 123456789;
var pos = 4;
var digit = ~~(number/Math.pow(10,pos))- ~~(number/Math.pow(10,pos+1))*10;
You could convert the number to a string and do the same thing:
parseInt((number + '').charAt(0))
If you want an existing method, convert it to a string and use charAt.
If you want a method that avoids converting it to a string, you could play games with dividing it by 10 repeatedly to strip off enough digits from the right -- say for 123456789, if you want the 3rd-from-right digit (6), divide by 10 3 times yielding 123456, then take the result mod 10 yielding 6. If you want to start counting digits from the left, which you probably do, then you need to know how many digits (base 10) are in the entire number, which you could deduce from the log base 10 of the number... All this is unlikely to be any more efficient than just converting it to a string.
function digitAt(val, index) {
return Math.floor(
(
val / Math.pow(10, Math.floor(Math.log(Math.abs(val)) / Math.LN10)-index)
)
% 10
);
};
digitAt(123456789, 0) // => 1
digitAt(123456789, 3) // => 4
A bit messy.
Math.floor(Math.log(Math.abs(val)) / Math.LN10)
Calculates the number of digits (-1) in the number.
var num = 123456;
var secondChar = num.toString()[1]; //get the second character
var number = 123456789
function return_digit(n){
r = number.toString().split('')[n-1]*1;
return r;
}
return_digit(3); /* returns 3 */
return_digit(6); /* returns 6 */
I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);