Rehman Khan
Rehman Khan

Reputation: 3

Uncaught TypeError: Cannot read property 'toString' of undefined

Why is my code not working? Chrome gives me the following error: Uncaught TypeError: Cannot read property 'toString' of undefined.

It works with 1,2,3,4,6,7,8,9 but does not work with 5,10,15,...

Please help me out.

Here is my javascript code:

<code><script>
function mmCal(val) {
    var a, b, c, d, e, f, g, h, i;
    a = val * 25.4;
    b = a.toString().split(".")[0];
    c = a.toString().split(".")[1];
    d = c.toString().substr(0, 1);
    e = +b + +1;
    f = b;

    if (d>5) {
        document.getElementById("txtt").value = e;
    } else {
        document.getElementById("txtt").value = f;
    }
}
</script></code>

Here is my html:

<code><input type="text" id="txt" value="" onchange="mmCal(this.value)"></code>
<code><input type="text" id="txtt" value=""></code>

Upvotes: 0

Views: 32352

Answers (3)

Ariel
Ariel

Reputation: 202

Strange way of rounding a number to an integer :-)

You are converting inches to millimeters, and then rounding that to an integer, right?

Why not use 'toFixed()' on the number? See: Number.prototype.toFixed()

I mean:

function mmCal(val) {
    var a, rounded;
    a = val * 25.4;
    rounded = a.toFixed();
    document.getElementById("txtt").value = rounded;
}

(you may also use "toFixed(0)" for the explicit precision).

Upvotes: 0

Wilfredo P
Wilfredo P

Reputation: 4076

As Sebnukem says

It doesn't work when a is an integer because there's no period to split your string, and that happens with multiples of 5.

But you could have a trick so use a % 1 != 0 to know wherther the value is a decimal see the code below:

function mmCal(val) {
var a, b, c, d, e, f, g, h, i;
a = val * 25.4;
    if(a % 1 != 0){
    b = a.toString().split(".")[0];
    c = a.toString().split(".")[1];
    }
    else{
    b = a.toString();
    c = a.toString();
    }
d = c.toString().substr(0, 1);
e = +b + +1;
f = b;
if (d>5) {
document.getElementById("txtt").value = e;
} else {
document.getElementById("txtt").value = f;
}
}

That could you help you.

LIVE DEMO

Upvotes: 1

sebnukem
sebnukem

Reputation: 8323

It doesn't work when a is an integer because there's no period to split your string, and that happens with multiples of 5.

Upvotes: 1

Related Questions