What's the best way to convert a number to a string in JavaScript?
like this:
var foo = 45;
var bar = '' + foo;
Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString()
See Performance tests here (not by me, but found when I went to write my own):
http://jsben.ch/#/ghQYR
Fastest based on the JSPerf test above: str = num.toString();
It should be noted that the difference in speed is not overly significant when you consider that it can do the conversion any way 1 Million times in 0.1 seconds.
Update: The speed seems to differ greatly by browser. In Chrome num + ''
seems to be fastest based on this test http://jsben.ch/#/ghQYR
Update 2: Again based on my test above it should be noted that Firefox 20.0.1 executes the .toString()
about 100 times slower than the '' + num
sample.
How to convert a string to an integer in JavaScript?
The simplest way would be to use the native Number
function:
var x = Number("1000")
If that doesn't work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods.
parseInt:
var x = parseInt("1000", 10); // you want to use radix 10
// so you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])
unary plus
if your string is already in the form of an integer:
var x = +"1000";
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
or, if you're going to be using Math.floor several times:
var floor = Math.floor;
var x = floor("1000.01");
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. Here I use floor.
var floor = Math.floor;
var x = floor(parseFloat("1000.01"));
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;
var x = round("1000"); //equivalent to round("1000",0)
What's the fastest way to convert String to Number in JavaScript?
There are 4 ways to do it as far as I know.
Number(x);
parseInt(x, 10);
parseFloat(x);
+x;
By this quick test I made, it actually depends on browsers.
https://jsben.ch/NnBKM
Implicit
marked the fastest on 3 browsers, but it makes the code hard to read… So choose whatever you feel like it!
Casting a number to a string in TypeScript
"Casting" is different than conversion. In this case, window.location.hash
will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:
window.location.hash = ""+page_number;
window.location.hash = String(page_number);
These conversions are ideal if you don't want an error to be thrown when page_number
is null
or undefined
. Whereas page_number.toString()
and page_number.toLocaleString()
will throw when page_number
is null
or undefined
.
When you only need to cast, not convert, this is how to cast to a string in TypeScript:
window.location.hash = <string>page_number;
// or
window.location.hash = page_number as string;
The <string>
or as string
cast annotations tell the TypeScript compiler to treat page_number
as a string at compile time; it doesn't convert at run time.
However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>
, then to <string>
:
window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
So it's easier to just convert, which handles the type at run time and compile time:
window.location.hash = String(page_number);
(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)
How to convert anything to a String safely in JavaScript
JavaScript allows you to modify the properties of pretty much any object that is accessible to your script, including Object.prototype
itself, meaning any object is vulnerable to "evil code" in the manner that you explained.
Only primitives are guaranteed to be safe, so the only way to ensure that "evil code" is never executed is to do something like this:
function safeToString(x) {
switch (typeof x) {
case 'object':
return 'object';
case 'function':
return 'function';
default:
return x + '';
}
}
Related Topics
What Values Can a Constructor Return to Avoid Returning This
How to Add New Array Elements at the Beginning of an Array in JavaScript
Why Avoid Increment ("++") and Decrement ("--") Operators in JavaScript
Why Is My Function Call That Should Be Scheduled by Settimeout Executed Immediately
Why Does JavaScript Handle the Plus and Minus Operators Between Strings and Numbers Differently
How to Loop Through an Array Containing Objects and Access Their Properties
How to Fix Error: Listen Eaddrinuse While Using Nodejs
Asynchronously Load Images with Jquery
Access Object Child Properties Using a Dot Notation String
Repeat a String in JavaScript a Number of Times
Angular 2 Sibling Component Communication
Warn User Before Leaving Web Page with Unsaved Changes
Differencebetween Parseint() and Number()
Why Doesn't Equality Check Work with Arrays
Comparing Date Part Only Without Comparing Time in JavaScript
How to Output an Iso 8601 Formatted String in JavaScript