I've always converted numbers to strings by adding an empty string to them:
var string = 1 + '';
However, JSLint complains of this method with Expected 'String' and instead saw ''''.
, and it does look a little ugly.
Is there a better way?
The toString() method is a built-in method of the JavaScript Number object that allows you to convert any number type value into its string type representation.
The toString() method is used with a number num as shown in above syntax using the '. ' operator. This method will convert num to a string. Parameters Used: This method accepts a single optional parameter base.
Use the String() object to convert a number to a string in TypeScript, e.g. const str = String(num) . When used as a function, the String object converts the passed in value to a primitive string and returns the result. Copied!
I believe that the JSLint approved way is to call .toString()
on the number:
var stringified = 1..toString(); // Note the use of the double .. to ensure the the interpreter knows // that we are calling the toString method on a number -- // not courting a syntax error. // You could also theoretically call 1["toString"];
(Sorry, it possibly would've been better to say this as a comment above but I haven't yet earned the right to post comments, so...)
Remember that jslint is not just validating whether your JavaScript will actually run, it is trying to enforce coding style with the aim of helping you produce more readable and maintainable code.
So 1 + ''
works, but isn't necessarily the most readable option for everybody while explicit casting options (see the other answers) should be readable for everybody. Of course if nobody else will ever see your code you need only worry about whether you will be able to understand it if you come back to it next month, or next year...
Don't forget that the following two statements don't produce the same result:
var s1 = 1 + 3 + ''; // gives '4' var s2 = '' + 1 + 3; // gives '13'
I assume 1 + ''
is just a simplification for discussion though, or why not just use '1'
in the first place?
You can use the .toString()
method like so:
var num = 1;
var str = num.toString();
There's also (at least in Chrome): String(1)
without new
.
var n = 1, s = String(n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With