![]() ![]() ParseInt and parseFloat are the two functions used for parsing strings to numbers. You can also do the same thing explicitly with the Number function. All of the tricks in the other answers (e.g., unary plus) involve implicitly coercing the type of the string to a number. One way is to parse it and the other way is to change its type to a Number. There are two main ways to convert a string to a number in JavaScript. Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite: var round = Math.round If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Or, if you're going to be using Math.floor several times: var floor = Math.floor If your string is or might be a float and you want an integer: var x = Math.floor("1000.01") // floor() automatically converts string to number ![]() If your string is already in the form of an integer: var x = +"1000" So you get a decimal number even with a leading 0 and an old browser () ![]() parseInt() var x = parseInt("1000", 10) // You want to use radix 10 If that doesn't work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods. The simplest way would be to use the native Number function: var x = Number("1000")
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |