Forum Moderators: open

Message Too Old, No Replies

why divide by 1?

How-to for converting strings to numbers

         

spritch2

2:27 am on Dec 2, 2004 (gmt 0)

10+ Year Member



can anyone explain whats going on below? why wud you want to share something by 1, wudn't it remain the same unless your turning a negative to positive (-75/1=75)

yt=(yt/1)+yi

the book i'm reading doesnt explain what its doing and the author didnt respond to my email, its in a function that moves a layer to simulate scrolling

yt is the current top of layer
yi is the increment to scroll

cheers

rocknbil

4:03 am on Dec 2, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Probably to keep it from concatenating as a string.

Bernard Marx

11:44 am on Dec 2, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What he means is, that the most concise way of converting a string that holds digits into a number is to divide by one. Javascript has no other option.

[BLUE]"290"/1 --> 290[/BLUE]

but

[BLUE]"hello"/1 --> NaN (not a number)[/BLUE]

I'm not sure it'll work properly unless you are using IE-only properties.
style.left and top properties usually contain the units too:

[BLUE]"290px"/1 --> NaN[/BLUE]

Use parseInt instead

[BLUE]parseInt("290px") --> 290[/BLUE]

adni18

1:27 pm on Dec 2, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm supposing that you could use eval():

strIng="3211";
strIng=eval(strIng);

Bernard Marx

2:43 pm on Dec 2, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you want an explicit conversion, use the Number constructor as a converter.

n = Number("123")

You'd only use eval for actual calculations in string form:

n = eval("4+6")

The problem with eval (or one of them) is that, if the string contains any non-digit characters, you'll end up referencing a non-existent, or invalid variable, resulting in a script error rather than just plain NaN, which can be tested for.

adni18

12:47 am on Dec 3, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've always used eval, for anything like this:

var q="1";
var b=1;
b=eval(eval(q)+eval(b));

Because otherwise, I get b=11.

spritch2

1:34 am on Dec 3, 2004 (gmt 0)

10+ Year Member



thats great thanks

dcrombie

11:24 am on Dec 3, 2004 (gmt 0)



These work in every version of JS back to Netscape 2 ;)

var newval = val - 0; // convert val to number 
var newval = val + ""; // convert val to string

Bernard Marx

12:15 pm on Dec 3, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Lots of things will work, but sometimes you might want to be explicit or safe.