1

i was trying to make a javascript program to convert a number between 20 and 100 to in words. so i wrote this-

var num = prompt("enter a number");
if (num>20 && num<100)
{
 words(num);
}
else alert("Please enter a number between 20 and 100");

function words(num)
{
var ones = ["","one","two","three","four","five","six", "seven","eight",  "nine"];
var tens = ["", "", "twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"];

var div= num/10;
var rem= num%10;

if (rem==0)
    document.write(num+" = "+tens[div]);
else
    document.write(num+" = "+tens[div]+" "+ones[rem]);

}

the problem is if i enter 30 ,40 like that numbers which are divisible by 10 i get correct output but if i enter 32 it will show "32 = undefined two". what did i do wrong? i am new to JS so dont know much.

2 Answers 2

2

32/10 is 3.2, not 3. You must round the result.

Change

 var div= num/10;

to

 var div= Math.floor(num/10);
Sign up to request clarification or add additional context in comments.

Comments

1

You should be doing

var rem= num%10;
var div= (num - rem)/10;

Because 25/10 = 2.5 not 2

Working Fiddle

4 Comments

i dont have enough reputation to down vote, dont know who did that .
This looks like a valid alternative. I'd like the downvoter to explain his vote.
I guess Math.floor() is relatively more complex operation then this direct Subtraction. Why to use it unnecessarily?
yeah,this looks valid and simple without using math().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.