Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JSLint approved way to convert a number to a string?

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?

like image 805
Samuel Cole Avatar asked Apr 28 '11 16:04

Samuel Cole


People also ask

Which function in Javassript converts a number to a string?

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.

How do you convert a number to a string in JavaScript?

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.

How do I convert a number to a string in TypeScript?

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!


4 Answers

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"]; 
like image 89
Sean Vieira Avatar answered Oct 16 '22 13:10

Sean Vieira


(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?

like image 20
nnnnnn Avatar answered Oct 16 '22 13:10

nnnnnn


You can use the .toString() method like so:

var num = 1;
var str = num.toString();
like image 29
KushalP Avatar answered Oct 16 '22 13:10

KushalP


There's also (at least in Chrome): String(1) without new.

var n = 1, s = String(n);
like image 34
Rudie Avatar answered Oct 16 '22 13:10

Rudie