简体   繁体   中英

not getting desired output in javascript

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.

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

Change

 var div= num/10;

to

 var div= Math.floor(num/10);

You should be doing

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

Because 25/10 = 2.5 not 2

Working Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM