not getting desired output in javascript - 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

Related

How to check a postal code in JavaScript?

I am trying to find out if this person needs to pay for shipping costs.
What I did is divide the postal code into numbers and letters. Next, I check to see if the input is between 1000 and 2000 and between AA en BB.
Problem: When I type in postal code 1000AA or 2000BB or something in between I always get the else answer even when the if statement is correct.
var sendingCost = 15;
var city = prompt("What city do you live in?");
var postalCode = prompt("What is your postal code?");
var postalCodeC = postalCode.slice(0, 3);
var postalCodeL = postalCode.slice(4, 5);
if (city == 'Amsterdam' && postalCodeC >= 1000 && postalCodeC <= 2000 && postalCodeL >= 'AA' && postalCodeL <= 'BB') {
alert('There is no sending cost')
} else {
alert('The sending cost is €15.')
};
Your slice() is not taking all four numbers of the postal code. Instead, use the following postalCode.slice(0, 4).
Have a look at the Mozilla docs regarding slice.
In the working code snippet below also note the following three lines.
var postalCodeC = Number(postalCode.slice(0, 4));
// converts the alphanumeric value from prompt to a number for better comparison.
var postalCodeL = postalCode.slice(-2).toUpperCase();
// converts the letters of the postal code to CAPS, this way Aa, AA or aa will be valid too.
var correctCity = city.toLowerCase() === 'amsterdam';
// the same here, convert city to lowercase letters and compare the input to 'amsterdam'
Working example.
var sendingCost = 15;
var city = prompt("What city do you live in?");
var postalCode = prompt("What is your postal code?");
var postalCodeC = Number(postalCode.slice(0, 4));
var postalCodeL = postalCode.slice(-2).toUpperCase();
var correctCity = city.toLowerCase() === 'amsterdam';
var withinPostalArea = postalCodeC >= 1000 && postalCodeC <= 2000 && postalCodeL >= 'AA' && postalCodeL <= 'BB';
console.log(postalCodeC);
console.log(postalCodeL);
if (correctCity && withinPostalArea) {
alert('There is no sending cost');
} else {
alert('The sending cost is €' + sendingCost);
};
NOTE: In order to help you debug these issues. console.log() the output to check the value of the variable and see if it is what you expect it to be.
Try this
var postcodec = +postcode.slice(0, 4);
var postcodeL = postcode.slice(4, 6);
As #Ivar mentioned, I don't think you understand how works the slice function. The first argument should be the the begin position and the second should be the end position. Thus, if you want to select only the first 4 numbers, and then the 2 letters you should use :
let postcode = "1500BD";
//Also, simply using slice will return a string, thus, you may want to convert it using Number();
let num = Number(postcode.slice(0, 4));
let letters = postcode.slice(4);

Accumulating an array's values - Javascript

I'm trying to accumulate a series of numbers in an array e6
Here is the relevant code.
e3 = prompt(e1 + ", Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
e6 = e3.split(',');
for(var a=0;a <= e6.length ;a++) {
e9=e9 + +e6[a];
}
document.write(e9) ;
However, what get's printed is NaN instead of the default sum of 15. Any ideas how to fix? Thank you.
Edit: Forgot to mention that i already had declared all my variables earlier.
var e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11;
Edit2: Here is my entire work in action. https://jsfiddle.net/nhz0Lnx8/
You should be looking only as far as e6.length-1, but the best solution is to avoid the off by one errors.
var e3 = prompt("Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
var e6 = e3.split(',');
var e9 = 0;
e3.split(',').map((x)=>{e9 += +x})
document.write(e9)
The error is in the for loop declaration:
"a <= e6.length" should be "a < e6.length" ("less than equal or equal" should be changed to "less than")
var e3 = prompt("Please enter few numbers (maximum of 6) separated by commas", "1,2,3,4,5");
var e6 = e3.split(',');
var e9 = 0;
for(var a=0;a < e6.length ;a++) {
e9 += parseInt( e6[a] );
}
document.write(e9) ;

how to divide a number a in a series of all whole numbers?

Hi sorry for asking this if this is a stupid question.
I would like to ask how to securely divide a number in Javascript that it will always
output the result in a way that it will output pure whole numbers.
example:
10 / 2 ---> 5, 5 ( it would be 2 fives so it is whole number )
BUT
10 / 3 ---> 3, 3, 4 ( it would have two 3 and one 4 so that it would still result to 10 )
10/3 will give you 3.333333..., never four... if you want to check is a number will give you "whole numbers" as you say, use modulo (%).
Modulo finds the remainder of division of one number by another.
For example
10%5 = 0 because 10 divided by 5 is a "whole number"
10%3 = 1 because the closest 10/3 is 3... 3x3=9... 10-9=1
So in your code, if you want to know if a number divided by another number is whole, you need to do
if (number1%number2 == 0) { ... }
Read more about it here
EDIT :
I read your question again and I think this fiddle is what you want
var number1 = 10,
number2 = 3;
if (number1 / number2 == 0) {
alert('the numbers are whole');
} else {
var remainder = number1%number2;
var wholes = Math.floor(number1 / number2);
var output = '';
for (var i = 0; i < (wholes - 1); i++) {
output+= number2 + ', ';
}
output += (number2 + remainder);
alert(output);
}
Whatever your result is,just pass it through the parseInt function,For Eg:-
Suppose your answer is 4.3,
The whole number close to it will can be accounted using,
parseInt(4.3)
Which equals 4.
Another posibility: make the number a string and walk all the elements
var a = 11 / 4;
//turn it into a string and remove all non-numeric chars
a = a.toString().replace(/\D/g, '');
//split the string in seperate characters
a = a.split("");
var num = new Array();
//convert back to numbers
for (var i = 0; i < a.length; i++) {
num.push(parseFloat(a[i]));
}
alert(num);
On a sidenote, you'll have to do some kind of rounding, to prevent eternally repeating numbers, like 10/3.
Here is a fiddle
Look at this very simple example:
var x = 10;
var y = 3;
var result = x/y;
var rest = x%y;
for (var i=0; i<y; i++) {
var output;
if(i==y-1){
output = parseInt(result + rest);
}
else{
output = parseInt(result);
}
alert(output);
}
http://jsfiddle.net/guinatal/469Vv/4/

JavaScript get max value min value average of an array

i want the user to enter a few marks and at the end i want to display the highest lowest average how many got a make of "A","B","C","D","F"
var highestMark=0;
var gradeAwarded;
var StudentArr= [Student];
var markArr = [mark];
var Student = prompt("Enter Student Name: ", "Name");
var mark = prompt("Enter Student Mark: ", 50);
var max = Math.max.apply(markArr); /* This about equal to Math.max(numbers[0], ...) or Math.max(5, 6, ..) */
var min = Math.min.apply(markArr);
if (mark < 0 || mark > 100) {
alert("Grate out of bounds");
} else if (mark >= 83) {
gradeAwarded = "A";
} else if (mark >= 70) {
gradeAwarded = "B";
} else if (mark >= 50) {
gradeAwarded = "C";
} else if (mark >= 0) {
gradeAwarded = "F";
}
document.write(min);
You can just sort the array and take the first and last value. For example:
arr = [3, 5, 2, 14];
arr.sort(function(x, y){return x-y});
min = arr[0]; // 2
max = arr[arr.length - 1]; // 14
Note that a custom comparison function is necessary since you want numerical sorting instead of lexical sorting of the string representation of the numbers. (Otherwise, "14" would be 'smaller' than "2", which is obviously not the way you want it.)
For the record, I agree with Mike Samuel on the other issues with your code.
Array.prototype.reduce allows you to fold over an array.
var min = markArr.reduce(
function (a,b) { return Math.min(a, b); },
Infinity);
var max = markArr.reduce(
function (a,b) { return Math.max(a, b); },
-Infinity);
var mean = markArr.reduce(function (a, b) { return a + b; }, 0)
/ markArr.length;
You've got a number of issues with your code though.
var markArr = [mark];
var Student = prompt("Enter Student Name: ", "Name");
var mark = prompt("Enter Student Mark: ", 50);
You're using mark to initialize markArr before reading mark.
Also, mark is read as a string.
You should reorder your statements so that you initialize variables before using them, and you
should make sure mark ends up as a numeric value.
var mark = +prompt("Enter Student Mark: ", 50);
The + before prompt coerces the string returned by prompt to a number.

South African ID Number Validate and Get Age and Gender

I've researched this but none of the code I use seems to work. South African ID numbers contain date of birth and gender. All I want is it to pull in that information and verify it when their ID number is entered into an input field, preferably in jQuery or javascript
Any help is appreciated,
Dawid
You could use Koenyn's regex validation, not so sure how a single-digit number (0-9?) from the input represents the gender but basing on this tool you provided and David Russell's Using Javascript to validate South African ID Numbers, here's an untested attempt:
UPDATE 1:
After following this thread, What is a South African ID number made up of?, I updated my implementation to include the gender and citizenship tests.
UPDATE 2:
Forgot to wrap the month number increment id_month + 1 within the date string fullDate, updating solution with Dawid's fix.
HTML Markup:
<div id="error"></div>
<form id="idCheck">
<p>Enter the ID Number: <input id="idnumber" /> </p>
<p> <input type="submit" value="Check" /> </p>
</form>
<div id="result"> </div>
Javascript:
function Validate() {
// first clear any left over error messages
$('#error p').remove();
// store the error div, to save typing
var error = $('#error');
var idNumber = $('#idnumber').val();
// assume everything is correct and if it later turns out not to be, just set this to false
var correct = true;
//Ref: http://www.sadev.co.za/content/what-south-african-id-number-made
// SA ID Number have to be 13 digits, so check the length
if (idNumber.length != 13 || !isNumber(idNumber)) {
error.append('<p>ID number does not appear to be authentic - input not a valid number</p>');
correct = false;
}
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
var fullDate = id_date + "-" + (id_month + 1) + "-" + id_year;
if (!((tempDate.getYear() == idNumber.substring(0, 2)) && (id_month == idNumber.substring(2, 4) - 1) && (id_date == idNumber.substring(4, 6)))) {
error.append('<p>ID number does not appear to be authentic - date part not valid</p>');
correct = false;
}
// get the gender
var genderCode = idNumber.substring(6, 10);
var gender = parseInt(genderCode) < 5000 ? "Female" : "Male";
// get country ID for citzenship
var citzenship = parseInt(idNumber.substring(10, 11)) == 0 ? "Yes" : "No";
// apply Luhn formula for check-digits
var tempTotal = 0;
var checkSum = 0;
var multiplier = 1;
for (var i = 0; i < 13; ++i) {
tempTotal = parseInt(idNumber.charAt(i)) * multiplier;
if (tempTotal > 9) {
tempTotal = parseInt(tempTotal.toString().charAt(0)) + parseInt(tempTotal.toString().charAt(1));
}
checkSum = checkSum + tempTotal;
multiplier = (multiplier % 2 == 0) ? 1 : 2;
}
if ((checkSum % 10) != 0) {
error.append('<p>ID number does not appear to be authentic - check digit is not valid</p>');
correct = false;
};
// if no error found, hide the error message
if (correct) {
error.css('display', 'none');
// clear the result div
$('#result').empty();
// and put together a result message
$('#result').append('<p>South African ID Number: ' + idNumber + '</p><p>Birth Date: ' + fullDate + '</p><p>Gender: ' + gender + '</p><p>SA Citizen: ' + citzenship + '</p>');
}
// otherwise, show the error
else {
error.css('display', 'block');
}
return false;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
$('#idCheck').submit(Validate);
DEMO: http://jsfiddle.net/chridam/VSKNx/
this is the validation regex we us at our company:
string IdExpression = #"(?<Year>[0-9][0-9])(?<Month>([0][1-9])|([1][0-2]))(?<Day>([0-2][0-9])|([3][0-1]))(?<Gender>[0-9])(?<Series>[0-9]{3})(?<Citizenship>[0-9])(?<Uniform>[0-9])(?<Control>[0-9])";
as far as using regex, it's really simple
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
There is a jQuery plugin that you can use. Check it out at http://www.verifyid.co.za/jqueryid
So there is an issue where if the ID number starts with 0 it gives the year of birth 1901 instead of 2001. #louwki mentioned it in his comment
I'm using your code but running into an issues when adding a id number
010101.... it gives the year of birth 1901 instead of 2001 any work around for this?
I have a work around assuming that there is no one older than a 100 years still alive who wants to get their date
// get first 6 digits as a valid date
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
// Add a 100 years to the current year if older than 100 years
if(id_year < (new Date()).getFullYear() - 100){
id_year+= 100
}
var fullDate = id_date + "-" + id_month + 1 + "-" + id_year;
DEMO: http://jsfiddle.net/dupies/5fwxvu6d/3/

Categories