Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: toString()

1. ## toString()

I'm average when it comes to math so I'm having trouble understanding the concept of how you convert an integer to a string, and what would be the best outcome? Can someone help me understand the toString() method please?

• Not much to it. See results of script below and look at comments.
Code:
```<script type="text/javascript">
var n1 = 3;  // a number
var n2 = 4;  // another number

var s1 = n1.toString();  // a string
var s2 = n2.toString();  // another string

var nadd = n1+n2;  // add numbers
var nsub = n1-n2;  // subtract numbers
var nmul = n1*n2;  // multiply numbers
var ndiv = n1/n2;  // divide numbers

var s = s1+s2;     // add (concatenate) strings
// cannot subtract, multiply or divide any two strings
// string would need to be converted to numbers before math can be done
// stings to numbers by Number(), parseInt(), parseFloat(); stringNumber * 1;

alert(nadd+'\n'+nsub+'\n'+nmul+'\n'+ndiv+'\n'+s);
</script>```

• Are you talking about how to *IMPLEMENT* toString()???

If so, are you talking about JavaSCRIPT or Java?? Because this sounds more like an exercise for a class in Java than for one in JavaSCRIPT. (This forum is for JavaSCRIPT. Almost the only similarity to Java is the first 4 letters of their names.)

If you are indeed asking how to implement toString()--that is, write your own as if the method didn't already exist--then do let us know. And confirm whether you are talking JavaScript or not.

• Ah, no this is completely for JavaScript. I'm just 'thrown off I guess you could say' by changing a number into a word, if that's how toString() works. Or do I have the understanding wrong?

What I mean by that is say my small script is

var one = 1;
var changed = one.toString();

alert(changed);

what will changed return and why??

So, from jmrker's example above, what I get out of it is it just changes the datatype itself and not the value, which is why the concatanation was possible and it didnt use math when using the + operator, at least thast what I got out of his code example. Is that what it is? so since you passed the two 'number' variables into the toString() method, we can now execute methods and treat these variables as if they are now datatype strings? Is it that simple? I'm probably just overthinking this.

• Well, yes and no.

Changing the datatype isn't at all as simple as you might think.

The internal representation of, say, the number 101 might be something like
Code:
`00000000 00000000 00000000 001100101`
That's a 4-byte integer. Or it might be stored as
Code:
`01000001 10010100 00000000 00000000`
that's a 4-byte floating point number (if I got my bits in the right spots...it's been at least a dozen years since I played with floating point at the bit level).

But that number *AS A STRING* would be
Code:
`00110001 00110000 00110001`
Which is actually THREE SEPARATE ASCII CHARACTERS. The character "1", the character "0", and then the character "1". (And, actually, each character is likely 2 bytes long, not one as shown, because JS is a Unicode language...but let's not get into that.)

The point is, as a *string*, there is nothing to distinguish "101" from "aba" or "\$?X" or any other three ASCII characters. Excepting, of course, that actual values of the characters.

So you wouldn't try to do
Code:
`"Axe" * "Woof"`
(in an attempt to multiply two strings).

And if JavaScript weren't such a forgiving language (a.k.a. an "untyped" language), then you wouldn't be able to do
Code:
`"101" * "371"`
As it happens, JMrker didn't tell the whole truth: If you attempt to do that with JavaScript, it *WILL* work and you *WILL* end up multiplying two numbers, just as if you had coded
Code:
`101 * 371`
That's because JavaScript (almost, but not quite, alone among common langusges--see also PHP) *will* coerce a string into a number if it thinks that doing so will allow it to perform a mathematical operation.

BUT...that is not the case with
Code:
`"101" + "371"`
where the result will be
Code:
`"101371"`
and that's because of an idiocy perpetrated in the design of Java many moons ago (and copied by JavaScript) wherein they decided to use the + operator for both mathematical addition and string concatenation. So if used with strings, you get concatenation. (PHP isn't my favorite language, but they got it right: PHP uses a period for string concatenation. Personally, I would have rather seen an operator that is otherwise unused, such as @ or # or \$, but oh well...)

• As it happens, JMrker didn't tell the whole truth: If you attempt to do that with JavaScript, it *WILL* work and you *WILL* end up multiplying two numbers, just as if you had coded
Code:

101 * 371

That's because JavaScript (almost, but not quite, alone among common langusges--see also PHP) *will* coerce a string into a number if it thinks that doing so will allow it to perform a mathematical operation.

BUT...that is not the case with
Code:

"101" + "371"

where the result will be
Code:

"101371"
The reason I did not "tell the whole truth" is because I find it easier to remember the rules
rather than the rules AND then the exceptions to the rules.

For example, while
var n = '101' * "371'
might work very nicely for some math calculations,
if the user has entered the '101' as '1O1' instead,
then when they get an error on the 'O'
because it looks similar to the '0'
they would not need to remember the exceptions.

• you can use + to coerce a number:

Code:
```"101" + "371" == "101371";

+"101" + +"371" == 472```

• Oh, I 100% agree with you, JMrker! I *NEVER* rely upon JavaScript converting strings to numbers for me.

I *always* do something like:
Code:
```var n = Number( someString );
if ( isNaN(n) ) { alert("doofus...I want a number"); }
...```
(Or parseInt if I want to insist that the value be an integer. Or ... )

I think it is a real hack to code stuff like
Code:
`var n = 1 * someString;`
I know it works. I just don't like it.

• 1* is messy, but Number() is several times slower...

i like operational casters:
Code:
`var n = +someString;`
Code:
`var n = +new Date;`
Code:
`var b = !!someString;`
strings are slightly more complicated:
Code:
`var s = ""+someString;`
Code:
`var s = ""+new Date;`

try to avoid the performance overhead of calling type functions (String, Number, Boolean), especially in loops and animation code.

• Originally Posted by rnd me
try to avoid the performance overhead of calling type functions (String, Number, Boolean), especially in loops and animation code.
I use the Number object all the time to convert a string to a number without any noticeable increase in execution time or any other overhead.

Whenever someone says something is faster or slower, I usually ask them to quantify how much faster or slower because if the order of magnitude is in nano or even micro-seconds I couldn't care less about the increase in execution time.

• Originally Posted by bullant
I use the Number object all the time to convert a string to a number without any noticeable increase in execution time or any other overhead.

Whenever someone says something is faster or slower, I usually ask them to quantify how much faster or slower because if the order of magnitude is in nano or even micro-seconds I couldn't care less about the increase in execution time.
I have to say that I fully agree with these remarks. But I do not really understand why Old Pedant objects to the efficient var n = 1 * someString;

• he didn't say he objects to it. He said he doesn't like it.

I don't like it either. It looks klunky and is a "poor man's" way of doing it imo.

• As you so often say, you are entitled to your opinion.

Why is var n = 1 * someString;
somehow less acceptable than
var n = +someString;

• Originally Posted by Philip M
As you so often say, you are entitled to your opinion.
yep, and I posted why I agree with Old Pedant

Originally Posted by Philip M
Why is var n = 1 * someString;
somehow less acceptable than
var n = +someString;
less acceptable to who?

• ## Just an observation ...

Just an observation ...
I'm not sure the operational casters idea by 'rnd me' are beneficial to me:
Code:
```<script type="text/javascript">
var s1 = '123';
var s2 = '456';
var n1 = +s1;
var n2 = +s2;
n = n1 + n2;
sa = +s1 + +s2;
ss = +s1 - +s2;
sm = +s1 * +s2;
sd = +s1 / +s2;

alert(n+'\n\n'+sa+'\n'+ss+'\n'+sm+'\n'+sd);
alert('Still concatenates: '+ +'123'+ +s1+'\nbut with () works OK: '+ (+'123'+ +s1));
</script>```
While the operations do work to cast the string to a number,
IMO, all the extra '+' characters in a row looks confusing to the casual coder.

For example, with a slip of the space bar and the expression
var n = +s1 + +s2;
becomes:
var n = +s1++s2;

•
Page 1 of 3 123 Last

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•