How to delete "px" from 245px - javascript

Whats a simple way to delete the last two characters of a string?

To convert 245px in 245 just run:
parseInt('245px', 10);
It retains only leading numbers and discards all the rest.

use
var size = parseInt('245px', 10);
where 10 is the radix defining parseInt is parsing to a decimal value
use parseInt but don't use parseInt without a radix
The parseInt() function parses a string and returns an integer.
The signature is parseInt(string, radix)
The second argument forces parseInt to use a base ten numbering system.
The default input type for ParseInt() is decimal (base 10).
If the number begins in "0", it is assumed to be octal (base 8).
If it begins in "0x", it is assumed to be hexadecimal
why? if $(this).attr('num') would be "08" parsInt without a radix would become 0

To convert a pixel value without the "px" at the end. use parseFloat.
parseFloat('245px'); // returns 245
Note: If you use parseInt, the value will be correct if the value is an integer. If the value is a decimal one like 245.50px, then the value will be rounded to 245.

This does exactly what you ask: remove last two chars of a string:
s.substr(0, s.length-2);

Surprisingly, the substring method s.substr(0, s.length-2); is actually quite a bit faster for removing the px (yes it isn't as clean looking, and if there is a space it will remain -- "250px" -> "250" vs "250 px" -> "250 ").
If you want to account for spaces (which you probably should) then using the .trim() function will actually slow down the substr test enough that the parseInt method actually becomes superior.
An added benefit of using parseInt(s, 10) is that you also get a type conversion and can immediately start to apply it to mathematical functions.
So in the end, it really depends on what you plan on doing with the result.
If it is display only, then using the substr method without a trim would probably be your best bet.
If you're just trying to see if the value without px is the same as another value s.substr(0, s.length-2) == 0, then using the substr method would be best, as "250 " == 250 (even with the space) will result as true
If you want to account for the possibility of a space, add it to another value, or to compute something with it, then you may want to consider going with the parseInt route.
http://jsperf.com/remove-px-from-coord
The tests on jspref account for a space. I also tried a s.split('px')[0] and s.replace(/ *px/g, '') function, both found to be slower.
Feel free to add additional test cases.

Although parseInt() is a good option but still it is good to have many other solutions
var pixels = '245px';
Number(pixels.replace('px', ''));

substr() is now a legacy feature; use substring() instead: (syntax is the same in this case)
str.substring(0, str.length-2);
Or, use slice():
str.slice(0, -2);
slice() looks much cleaner, IMO. Negative values count back from the end.

Check http://www.w3schools.com/jsref/jsref_substr.asp
In your case would be something like
string.substr(0, string.length - 2)

I prefer:
"245px".replace(/px/,'')*1
since it's not surrounding the input.
Also, the *1 is for casting it to int.

Related

Getting the numeric value after the hyphen in a string

How can I extract and get just the numeric value after the hyphen in a string?
Here is the input string:
var x = "-2147467259"
After some processing.... return:
alert(2147467259)
How do I accomplish this?
You could replace away the hyphen:
alert(+x.replace("-", ""));
And yes, the + is important. It converts a string to a number; so you're removing the hypen by replacing it with nothing, and then essentially casting the result of that operation into a number. This operation will also work if no hyphen is present.
You could also use substr to achieve this:
alert(+x.substr(1));
You could also use parseInt to convert the string to a number (which will end up negative if a hyphen is persent), and then find its absolute value:
alert(Math.abs(parseInt(x, 10));
As Bergi notes, if you can be sure that the first character in the string is always a hyphen, you can simple return its negative, which will by default cast the value into a number and then perform the negative operation on it:
alert(-x);
You could also check to see if the number is negative or positive via a tertiary operator and then perform the respective operation on it to ensure that it is a positive Number:
x = x >= 0 ? +x : -x;
This may be cheaper in terms of performance than using Math.abs, but the difference will be minuscule either way.
As you can see, there really are a variety of ways to achieve this. I'd recommend reading up on JavaScript string functions and number manipulation in general, as well as examining JavaScript's Math object to get a feel for what tools are available to you when you go to solve a problem.
How about:
Math.abs(parseInt("-2147467259"))
Or
"-2147467259".replace('-','')
or
"-2147467259".replace(/\-/,'')
#1 option is converting the string to numbers. The #2 approach is removing all - from the string and the #3 option even though it will not be necessary on this example uses Regular Expression but I wanted to show the possibility of using RegEx in replace situations.
If you need a number as the final value #1 is your choice if you need strings #2 is your choice.

Javascript convert string to integer

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.
1,700.00 + 500.00
returns 1,700.00500.00
So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.
The most relevant pages I read to resolve this were this question and this page. However when I use
parseInt(string, radix)
it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).
var a="1,700.00";
var b=500.00;
parseInt(a, 10);
Basic Answer
The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:
var num = '1,700.00';
num = num.replace(/\,/g,'');
This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.
num = parseInt(num);
Do this for each of your string numbers before adding them and everything should work.
More information
How the replace works:
More information on replace at mdn:
`/` - start
`\,` - escaped comma
`/` - end
`g` - search globally
The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.
Regular Expressions
A great tool to test regular expressions: Rubular and more info about them at mdn
If you are looking for a good tutorial here is one.
ParseInt and Rounding, parseFloat
parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:
2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`
For more information on parseInt look at mdn.
parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by #fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.
Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace() to get rid of each appearance of ,.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment #Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by #EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike #EpiphanyMachine solution. So you will be your own judge.
try this :
parseFloat(a.replace(/,/g, ''));
it will work also on : 1,800,300.33
Example :
parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01
Javascript doesn't understand that comma. Remove it like this:
a.replace(',', '')
Once you've gotten rid of the comma, the string should be parsed with no problem.

Javascript alert number starting with 0

I have a button where in the code behind I add a onclick and I pass a unique ID which will be passed to the js function. The id starts with a 0.
It wasn't working and eventually I figured out that the number, id, it was passing was wrong...
Ie. see this: js fiddle
It works with a ' at the start and end of the number. Just wondering why 013 turns to 11. I did some googling and couldn't find anything...
Cheers
Robin
Edit:
Thanks guys. Yep understand now.
As in this case the 0 at the start has a meaning, here the recipient ID in a mailing list, I will use '013' instead of just 013, i.e. a string. I can then split the values in js as each of the 3 values represents a different id which will always be only 1 character long, i.e. 0-9.
A numeric literal that starts with a 0 is treated as an octal number. So 13 from base 8 is 11 in base 10...
Octal numeric literals have been deprecated, but still work if you are not in strict mode.
(You didn't ask, but) A numeric literal that starts with 0x is treated as hexadecimal.
More info at MDN.
In your demo the parameter is called id, which implies you don't need to do numerical operations on it - if so, just put it in quotes and use it as a string.
If you need to be able to pass a leading zero but still have the number treated as base 10 to do numerical operations on it you can enclose it in quotes to pass it as a string and then convert the string to a number in a way that forces base 10, e.g.:
something('013');
function something(id){
alert(+id); // use unary plus operator to convert
// OR
alert(parseInt(id,10)); // use parseInt() to convert
}
Demo: http://jsfiddle.net/XYa6U/5/
013 is octal, not decimal, it's equal 11 in decimal
You should note that 013 starts with a 0. In Javascript, this causes the number to be considered octal. In general you'll want to use the decimal, and hexadecimal number systems. Occasionally though, octal numbers are useful, as this question shows.
I hope this helps! :)
If the first digit of a number is a zero, parseInt interprets the number as an octal.
You can specify a base of ten like this:
parseInt(numberString, 10)
You could also remove such zeros with a regex like this (the result will be a string):
numberString.replace(/^0+/g, '');

How to get numerical value from String containing digits and characters

Is there any built in method to get which can parse int from string ("23px")?
I know I can use substring and then parseInt but I want to know if there is any other way available to do this.
parseInt will grab the first set of contiguous numbers:
parseInt('23px');
returns 23.
If there is any chance there will be leading zeros, use a radix:
parseInt('23px', 10);
which is a good habit in general.
parseInt can do it. Just use:
var num = parseInt("23px", 10);
It will parse the integer part and ignore the rest.

javascript/jquery: quick way to retrieve numeric from length attributes

I have attributes which denotes "5 px", "8px" "6em" and possible some others which I currently cannot think of right now.
I'm interested in only the numeric value (ie 5, 8 or 6.) I know i can do some regex but I'm wondering is there a short, documented, cross browser and readable jquery / javascript function out there which already provides this?
regards,
Jeroen.
PS not sure if the wording in the title is correct please advice for alternatives.
Use parseInt function:
var str = '5px';
alert(parseInt(str, 10)); // 5
Note that second argument of 10 represents base 10 there.
In case they ever come back as 08px, (leading zero), use the radix of 10. Otherwise parseint() thinks your number is in octal.
var value = parseInt(str, 10);
It is probably never going to happen being returned from jQuery as a CSS property value, but a good habit to get into.
A combination of parseInt/parseFloat (see the other answers) is probably your best bet, but just for kicks (and if you want to make your code completely unreadable), you can always use a Regex with extra cheese:
+(str.match(/(-?\d+(?:\.\d+)?)/)||[,0])[1]
The + operator converts the result to a Number, ||[,0] provides a default array if there's no number in str. [,0] might not work in all browsers, but [0,0] will.
:)

Categories

Resources