error message instead of NaN output and negative 'Nett Payment' output - javascript

var vDiscountPercent;
var vGrossPayment;
var vTicketType;
vTicketType = prompt(" What type of Tickets is required?");
document.write("The Ticket Type is: " + vTicketType);
var vTicketQty;
vTicketQty = prompt("How many Tickets are required?");
document.write("<br/>");
document.write("The Ticket Qty is: " + vTicketQty + "<br/>");
var vTicketQty = parseInt(vTicketQty);
if (isNaN(parseInt(vTicketQty))) {
vTicketQty = 0;
}
if (vTicketQty <= 0) {
document.write("Invalid Qty" + "<br/>");
} else {
vTicketPrice = calcPrice(vTicketType);
if (vTicketPrice == -1) {
document.write("Invalid Ticket Type" + "<br/>");
} else {
document.write("Ticket Price is: " + vTicketPrice + "<br/>");
}
var vTotalPayment = calcTotal(vTicketPrice, vTicketQty);
if (vTotalPayment > 0) {
document.write("Total payment required is: $" + vTotalPayment + "<br/>");
} else {
document.write("Invalid data supplied" + "<br/>");
}
}
function calcTotal(vTicketPrice, vTicketQty) {
return vTicketPrice * vTicketQty;
}
function calcPrice(vTicketType) {
var vTicketPrice;
if (vTicketType.toLowerCase() == "a") {
vTicketPrice = 100;
} else if (vTicketType.toLowerCase() == "b") {
vTicketPrice = 75;
} else if (vTicketType.toLowerCase() == "c") {
vTicketPrice = 50;
} else {
vTicketPrice = -1;
}
return vTicketPrice;
}
vGrossPayment = vTotalPayment;
var vGrossPayment = calcDiscountPercent(vGrossPayment);
function calcDiscountPercent(vGrossPayment) {
if (vGrossPayment < 200) {
document.write("Discount Percent: 0%");
vDiscountPercent = 0;
} else if (vGrossPayment < 400) {
document.write("Discount Percent: 5%");
vDiscountPercent = 0.05;
} else if (vGrossPayment < 600) {
document.write("Discount Percent: 7.5%");
vDiscountPercent = 0.075;
} else if (vGrossPayment > 600) {
document.write("Discount Percent: 10%");
vDiscountPercent = 0.10;
} else {
document.write("No discount");
}
return vDiscountPercent;
}
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent);
function applyDiscount(vTotalPayment, vDiscountPercent) {
return vTotalPayment * (vDiscountPercent * 100) / 100;
}
document.write("<br/>" + "Discount Amount: $" + applyDiscount);
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount);
function calcDiscountAmount(vGrossPayment, vDiscountPercent) {
return vTotalPayment - applyDiscount;
}
document.write("<br/>" + "Nett Payment: $" + vNettPayment);
At the moment when I enter a value that isn't between 1 to 100 in 'vTicketQty' the output is 'NaN' for 'Nett Payment' and 'Discount Amount', how do I get the output value to show an error message instead of NaN?
Also when I don't enter 'a' , 'b' or 'c' for 'vTicketType' the output for 'Nett Payment" is negative, again how do I get the output to show an error message instead?

use like this .
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent)|0;
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount)|0;
variable is invalid it's return with '0'
var vDiscountPercent;
var vGrossPayment;
var vTicketType;
vTicketType = prompt(" What type of Tickets is required?");
document.write("The Ticket Type is: " + vTicketType);
var vTicketQty;
vTicketQty = prompt("How many Tickets are required?");
document.write("<br/>");
document.write("The Ticket Qty is: " + vTicketQty + "<br/>");
var vTicketQty = parseInt(vTicketQty);
if (isNaN(parseInt(vTicketQty))) {
vTicketQty = 0;
}
if (vTicketQty <= 0) {
document.write("Invalid Qty" + "<br/>");
} else {
vTicketPrice = calcPrice(vTicketType);
if (vTicketPrice == -1) {
document.write("Invalid Ticket Type" + "<br/>");
} else {
document.write("Ticket Price is: " + vTicketPrice + "<br/>");
}
var vTotalPayment = calcTotal(vTicketPrice, vTicketQty);
if (vTotalPayment > 0) {
document.write("Total payment required is: $" + vTotalPayment + "<br/>");
} else {
document.write("Invalid data supplied" + "<br/>");
}
}
function calcTotal(vTicketPrice, vTicketQty) {
return vTicketPrice * vTicketQty;
}
function calcPrice(vTicketType) {
var vTicketPrice;
if (vTicketType.toLowerCase() == "a") {
vTicketPrice = 100;
} else if (vTicketType.toLowerCase() == "b") {
vTicketPrice = 75;
} else if (vTicketType.toLowerCase() == "c") {
vTicketPrice = 50;
} else {
vTicketPrice = -1;
}
return vTicketPrice;
}
vGrossPayment = vTotalPayment;
var vGrossPayment = calcDiscountPercent(vGrossPayment);
function calcDiscountPercent(vGrossPayment) {
if (vGrossPayment < 200) {
document.write("Discount Percent: 0%");
vDiscountPercent = 0;
} else if (vGrossPayment < 400) {
document.write("Discount Percent: 5%");
vDiscountPercent = 0.05;
} else if (vGrossPayment < 600) {
document.write("Discount Percent: 7.5%");
vDiscountPercent = 0.075;
} else if (vGrossPayment > 600) {
document.write("Discount Percent: 10%");
vDiscountPercent = 0.10;
} else {
document.write("No discount");
}
return vDiscountPercent;
}
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent)|0;
function applyDiscount(vTotalPayment, vDiscountPercent) {
return vTotalPayment * (vDiscountPercent * 100) / 100;
}
if(applyDiscount){
document.write("<br/>" + "Discount Amount: $" + applyDiscount)
}
else{
document.write("<br/>Error-something not right in Discount Amount")
}
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount)|0;
function calcDiscountAmount(vGrossPayment, vDiscountPercent) {
return vTotalPayment - applyDiscount;
}
if(vNettPayment){
document.write("<br/>" + "Nett Payment: $" + vNettPayment);
}
else{
document.write("<br/>Error-something not right in Nett Payment ")
}

Related

how to show when a value is zero or below

I am busy whith a monopaly game.It is almost done but I cant find out how to
show when the user is bankrupt
I would prefer to use my isBankrupt function to check if the persons money is less then or equal to zero, if so it sould log that that user is bankrupt
I have tried including an if statement in my dice function but it is not working.
let player = [
{
name: "",
money: 1000,
position: 0,
propertys: [
{
name: "raslow",
position: 2,
cost: 20
},
{
name: "luadiam",
position: 4,
cost: 50
},
{
name: "eldo",
position: 6,
cost: 100
},
{
name: "erasmia",
position: 8,
cost: 200
}
],
dice() {
let random = Math.floor(Math.random() * 11);
for (var i = 0; i < player[0].propertys.length; i++) {
if (random === player[0].propertys[i].position) {
console.log("you are safe");
break;
}
else if (random == 1 || random == 10) {
console.log("you are safe");
break;
}
else if(random !== player[0].propertys[i].position){
if (random === 3) {
console.log("you have landed on Columbus");
player[0].money -= 20;
player[1].money += 20;
break;
}
if (random === 5) {
console.log("you have landed on Essex");
player[0].money -= 50;
player[1].money += 50;
break;
}
if (random === 7) {
console.log("you have landed on Eugene ");
player[0].money -= 100;
player[1].money += 100;
break;
}
if (random === 9) {
console.log("you have landed on Diego ");
player[0].money -= 200;
player[1].money += 200;
break;
}
}
}
console.log(player[0].name + ' ' + "has" + " " + player[0].money);
console.log(player[1].name + ' '+ "has" + " " + player[1].money);
},
isBankrupt(){
while(player[0].money <= 0){
console.log(player[0].name + ' ' + 'is Bankrupt')
}
}
},
{
name: "",
money: 1000,
position: 0,
property: [
{
name: "Columbus",
position: 3,
cost: 20
},
{
name: "Essex",
position: 5,
cost: 50
},
{
name: "Eugene",
position: 7,
cost: 100
},
{
name: "Diego",
position: 9,
cost: 200
}
],
dice() {
let random = Math.floor(Math.random() * 11);
for (var i = 0; i < player[0].propertys.length; i++) {
if (player[1].money <= 0) {
break;
}
if (random === player[0].propertys[i].position) {
console.log("you are safe");
break;
}
else if (random == 1 || random == 10) {
console.log("you are safe");
break;
}
else if(random !== player[0].propertys[i].position) {
if (random === 2) {
console.log("you have landed on raslow");
player[0].money += 20;
player[1].money -= 20;
break;
}
if (random === 4) {
console.log("you have landed on luadiam ");
player[1].money -= 50;
player[0].money += 50;
break;
}
if (random === 6) {
console.log("you have landed on eldo ");
player[1].money -= 100;
player[0].money += 100;
break;
}
if (random === 8) {
console.log("you have landed on erasmia ");
player[1].money -= 200;
player[0].money += 200;
break;
}
}
}
console.log(player[0].name + ' ' + "has" + " " + player[0].money);
console.log(player[1].name + ' ' + "has" + " " + player[1].money);
},
isBankrupt(){
while(player[0].money <= 0){
console.log(player[0].name + ' ' + 'is Bankrupt')
}
}
}
];
function playgame() {
player[0].name = prompt('Enter player1 name')
player[1].name = prompt('Enter player2 name')
}
Please help out
You can check for bankruptcy with a simple if statement:
if (player[0].money <= 0) {
console.log(player[0].name + ' ' + 'is Bankrupt');
}
If you want to put it into a function so that you can call it for each player -- instead of writing multiple checks into your code -- you can call isBankrupt with the index of the current player and write the function like this:
function isBankrupt(p) {
// p = the current player
if (player[p].money <= 0) {
console.log(player[p].name + ' ' + 'is Bankrupt');
}
}

Logic issue in minesweeper

--SOLVED--
I was just forgetting to reset the number of flags after each game.
I'm having issues with the number of flags in my minesweeper game. For some reason, sometimes when I flag a tile the number of flags increases by more than 1. Sometimes it increases by 3, sometimes 4, sometimes 7. I can't find the issue in my logic, so I was hoping to get another set of eyes on it.
The only sort of pattern I can see when it adds more flags than it should, i.e. the flags variable is incremented more than once, is when I flag a tile that is mostly surrounded by revealed tiles.
Javascript:
var flags = 0;
var trueFlags = 0;
function newGame() {
var cols = $("#width").val();
var rows = $("#height").val();
if (cols < 8 || rows < 8) {
return;
}else if (cols > 40 || rows > 30) {
return;
}
boardClear();
possibleBombs = (rows * cols) - 1;
numBombs = 0;
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= cols; j++) {
if (numBombs < possibleBombs) {
var q = Math.floor(Math.random() * 50);
if (0 <= q && q <= 2) {
numBombs += 1;
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 0 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + 'data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
$("#board").append("<br/>");
}
$(".controls h2").text("Bombs to go: " + numBombs);
$(".tile").css("background-color", "white");
$(".tile").width(15);
$(".tile").height(15);
console.log("bombs: " + numBombs, "possible: " + possibleBombs);
$(".tile").click(function(e) {
if (e.shiftKey) {
flagKey($(this));
$(".controls h2").text("Bombs to go: " + (numBombs - flags));
}
else if ($(this).data("contains") == 0) {
console.log("you lose");
boardClear();
newGame();
return;
}
else {
revealNeighbors($(this));
// if (gameWon() == true) {
// alert("You have won!");
// newGame();
// }
return;
}
});
}
function boardClear() {
$("#board").empty();
}
function revealNeighbors(tile) {
var cordsx = tile.data("row");
var cordsy = tile.data("col");
// tile has bomb
if(tile.data("contains") == 0) {return;}
// tile is flagged
else if(tile.data("flagged") == true){return;}
// tile has been revealead already
else if(tile.prop("revealed") == true) {return;}
// reveal the tile
var tileBombs = nearbyBombCount(tile);
tile.prop("revealed", true);
tile.text(tileBombs);
tile.css("background-color", "grey");
if (tileBombs == 0){tile.text("");}
else if(tileBombs != 0) {return;}
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
if (cordsx + i < 1 || cordsy + j < 1) {continue;}
else if (cordsx + i > $("#width").val() || cordsy + j > $("#height").val()) {continue;}
else if (i == 0 && j == 0) {continue;}
var neighbor = $('.tile[data-row="' + (cordsx+i) + '"][data-col ="'+(cordsy+j)+'"]');
revealNeighbors(neighbor);
}
}
}
function nearbyBombCount(tile) {
var cx = tile.data("row");
var cy = tile.data("col");
var nearbyBombs = 0;
for (var n = -1; n < 2; n++) {
for (var m = -1; m < 2; m++) {
if (cx + n < 1 || cy + m < 1) {continue;}
else if (cx + n > $("#width").val() || cy + m > $("#height").val()) {continue;}
var neighbor = $('.tile[data-row="' + (cx+n) + '"][data-col ="'+(cy+m)+'"]');
if (neighbor.data("contains") == 0) {
nearbyBombs++;
}
}
}
return nearbyBombs;
}
function flagKey(tile) {
// tile is already revealed
if (tile.data("revealed") == true) {
return;
}
// tile is already flagged
else if (tile.data("flagged") == true) {
tile.data("flagged", false);
tile.css("background-color", "white");
flags--;
// contains bomb
if (tile.data("contains") == 0) {
trueFlags--;
}
return;
}
// tile not flagged
else if (tile.data("flagged") == false) {
flags++;
tile.data("flagged", true);
tile.css("background-color", "red");
// contains bomb
if (tile.data("contains") == 0) {
trueFlags++;
console.log(trueFlags);
}
}
else {
return;
}
}
My guess is that there's something wrong with my revealNeighbors() function or it's some scope issue, but I can't for the life of me figure out what it is.
Hi I change a litle and works fine
<html>
<head>
<style>
.tile{padding:5px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Width : <input type="text" id="width" value="15" /> Height :<input type="text" id="height" value="15" /><input type="button" onclick="newGame()" id="btnstart" value="start" />
<br />
<div>
<div id="board" >
</div>
</div>
<script>
var flags = 0;
var trueFlags = 0;
function newGame() {
var cols = $("#width").val();
var rows = $("#height").val();
if (cols < 8 || rows < 8) {
return;
}else if (cols > 40 || rows > 30) {
return;
}
boardClear();
possibleBombs = (rows * cols) - 1;
numBombs = 0;
for (var i = 1; i <= rows; i++) {
for (var j = 1; j <= cols; j++) {
if (numBombs < possibleBombs) {
var q = Math.floor(Math.random() * 50) + 1;
if (q <= 2) {
numBombs += 1;
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 0 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + 'data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + ' data-col = ' + j + ' data-contains = ' + 1 + ' data-flagged = ' + false + '></button>').prop("revealed", false);
}
}
$("#board").append("<br/>");
}
$(".controls h2").text("Bombs to go: " + numBombs);
$(".tile").css("background-color", "white");
$(".tile").width(15);
$(".tile").height(15);
console.log("bombs: " + numBombs, "possible: " + possibleBombs);
$(".tile").click(function (e) {
if (e.shiftKey) {
flagKey($(this));
$(".controls h2").text("Bombs to go: " + (numBombs - flags));
}
else if ($(this).data("contains") == 0) {
console.log("you lose");
boardClear();
newGame();
return;
}
else {
revealNeighbors($(this));
// if (gameWon() == true) {
// alert("You have won!");
// newGame();
// }
return;
}
});
}
function boardClear() {
$("#board").empty();
}
function revealNeighbors(tile) {
var cordsx = tile.data("row");
var cordsy = tile.data("col");
// tile has bomb
if(tile.data("contains") == 0) {return;}
// tile is flagged
else if(tile.data("flagged") == true){return;}
// tile has been revealead already
else if(tile.prop("revealed") == true) {return;}
// reveal the tile
var tileBombs = nearbyBombCount(tile);
tile.prop("revealed", true);
tile.text(tileBombs);
tile.css("background-color", "grey");
if (tileBombs == 0){tile.text("");}
else if(tileBombs != 0) {return;}
for (var i = -1; i <= 1; i++) {
for (var j = -1; j <= 1; j++) {
if (cordsx + i < 1 || cordsy + j < 1) {continue;}
else if (cordsx + i > $("#width").val() || cordsy + j > $("#height").val()) {continue;}
else if (i == 0 && j == 0) {continue;}
var neighbor = $('.tile[data-row="' + (cordsx+i) + '"][data-col ="'+(cordsy+j)+'"]');
revealNeighbors(neighbor);
}
}
}
function nearbyBombCount(tile) {
var cx = tile.data("row");
var cy = tile.data("col");
var nearbyBombs = 0;
for (var n = -1; n < 2; n++) {
for (var m = -1; m < 2; m++) {
if (cx + n < 1 || cy + m < 1) {continue;}
else if (cx + n > $("#width").val() || cy + m > $("#height").val()) {continue;}
var neighbor = $('.tile[data-row="' + (cx+n) + '"][data-col ="'+(cy+m)+'"]');
if (neighbor.data("contains") == 0) {
nearbyBombs++;
}
}
}
return nearbyBombs;
}
function flagKey(tile) {
// tile is already revealed
if (tile.data("revealed") == true) {
return;
}
// tile is already flagged
else if (tile.data("flagged") == true) {
tile.data("flagged", false);
tile.css("background-color", "white");
flags--;
// contains bomb
if (tile.data("contains") == 0) {
trueFlags--;
}
return;
}
// tile not flagged
else if (tile.data("flagged") == false) {
flags++;
tile.data("flagged", true);
tile.css("background-color", "red");
// contains bomb
if (tile.data("contains") == 0) {
trueFlags++;
console.log(trueFlags);
}
}
else {
return;
}
}
</script>
</body>
</html>

how to modify below function to read 3 decimal places

I am using tafgeet javascript function to convert numbers into Arabic words, but the problem is that it supports only 2 decimal places, how can I modify the function to make it read 3 decimal places:
It actually translates upto a million on the left hand side, so it would be possible to apply the same methodology on the right side.
I tried to fiddle with it, but it doesn't work. I am posting the original javascript.
/**
* TafgeetJS module.
* #module TafgeetJS
* #description Converts currency digits into written Arabic words
* #author Mohammed Mahgoub <mmahgoub#gmail.com>
*/
function Tafgeet(digit) {
var currency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "SDG";
//Split fractions
var splitted = digit.toString().split(".");
this.fraction = 0;
if (splitted.length > 1) {
var fraction = parseInt(splitted[1]);
if (fraction >= 1 && fraction <= 99) {
this.fraction = splitted[1].length === 1 ? fraction * 10 : fraction;
} else {
//trim it
var trimmed = Array.from(splitted[1]);
this.fraction = "" + trimmed[0] + trimmed[1];
}
}
this.digit = splitted[0];
this.currency = currency;
}
Tafgeet.prototype.parse = function () {
var serialized = [];
var tmp = [];
var inc = 1;
var count = this.length();
var column = this.getColumnIndex();
if (count >= 16) {
console.error("Number out of range!");
return;
}
//Sperate the number into columns
Array.from(this.digit.toString()).reverse().forEach(function (d, i) {
tmp.push(d);
if (inc == 3) {
serialized.unshift(tmp);
tmp = [];
inc = 0;
}
if (inc == 0 && count - (i + 1) < 3 && count - (i + 1) != 0) {
serialized.unshift(tmp);
}
inc++;
});
// Generate concatenation array
var concats = []
for (i = this.getColumnIndex(); i < this.columns.length; i++) {
concats[i] = " و";
}
//We do not need some "و"s check last column if 000 drill down until otherwise
if (this.digit > 999) {
if (parseInt(Array.from(serialized[serialized.length - 1]).join("")) == 0) {
concats[parseInt(concats.length - 1)] = ""
for (i = serialized.length - 1; i >= 1; i--) {
if (parseInt(Array.from(serialized[i]).join("")) == 0) {
concats[i] = ""
} else {
break;
}
}
}
}
var str = "";
str += "فقط ";
if (this.length() >= 1 && this.length() <= 3) {
str += this.read(this.digit);
} else {
for (i = 0; i < serialized.length; i++) {
var joinedNumber = parseInt(serialized[i].reverse().join(""));
if (joinedNumber == 0) {
column++;
continue;
}
if (column == null || column + 1 > this.columns.length) {
str += this.read(joinedNumber);
} else {
str += this.addSuffixPrefix(serialized[i], column) + concats[column];
}
column++;
}
}
if (this.currency != "") {
if (this.digit >= 3 && this.digit <= 10) {
str += " " + this.currencies[this.currency].plural;
} else {
str += " " + this.currencies[this.currency].singular;
}
if (this.fraction != 0) {
if (this.digit >= 3 && this.digit <= 10) {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fractions;
} else {
str +=
" و" +
this.read(this.fraction) +
" " +
this.currencies[this.currency].fraction;
}
}
}
str += " لا غير";
return str;
};
Tafgeet.prototype.addSuffixPrefix = function (arr, column) {
if (arr.length == 1) {
if (parseInt(arr[0]) == 1) {
return this[this.columns[column]].singular;
}
if (parseInt(arr[0]) == 2) {
return this[this.columns[column]].binary;
}
if (parseInt(arr[0]) > 2 && parseInt(arr[0]) <= 9) {
return (
this.readOnes(parseInt(arr[0])) +
" " +
this[this.columns[column]].plural
);
}
} else {
var joinedNumber = parseInt(arr.join(""));
if (joinedNumber > 1) {
return this.read(joinedNumber) + " " + this[this.columns[column]].singular;
} else {
return this[this.columns[column]].singular;
}
}
};
Tafgeet.prototype.read = function (d) {
var str = "";
var len = Array.from(d.toString()).length;
if (len == 1) {
str += this.readOnes(d);
} else if (len == 2) {
str += this.readTens(d);
} else if (len == 3) {
str += this.readHundreds(d);
}
return str;
};
Tafgeet.prototype.readOnes = function (d) {
if (d == 0) return;
return this.ones["_" + d.toString()];
};
Tafgeet.prototype.readTens = function (d) {
if (Array.from(d.toString())[1] === "0") {
return this.tens["_" + d.toString()];
}
if (d > 10 && d < 20) {
return this.teens["_" + d.toString()];
}
if (d > 19 && d < 100 && Array.from(d.toString())[1] !== "0") {
return (
this.readOnes(Array.from(d.toString())[1]) +
" و" +
this.tens["_" + Array.from(d.toString())[0] + "0"]
);
}
};
Tafgeet.prototype.readHundreds = function (d) {
var str = "";
str += this.hundreds["_" + Array.from(d.toString())[0] + "00"];
if (
Array.from(d.toString())[1] === "0" &&
Array.from(d.toString())[2] !== "0"
) {
str += " و" + this.readOnes(Array.from(d.toString())[2]);
}
if (Array.from(d.toString())[1] !== "0") {
str +=
" و" +
this.readTens(
(Array.from(d.toString())[1] + Array.from(d.toString())[2]).toString()
);
}
return str;
};
Tafgeet.prototype.length = function () {
return Array.from(this.digit.toString()).length;
};
Tafgeet.prototype.getColumnIndex = function () {
var column = null;
if (this.length() > 12) {
column = 0;
} else if (this.length() <= 12 && this.length() > 9) {
column = 1;
} else if (this.length() <= 9 && this.length() > 6) {
column = 2;
} else if (this.length() <= 6 && this.length() >= 4) {
column = 3;
}
return column;
};
Tafgeet.prototype.ones = {
_1: "واحد",
_2: "ٱثنين",
_3: "ثلاثة",
_4: "أربعة",
_5: "خمسة",
_6: "ستة",
_7: "سبعة",
_8: "ثمانية",
_9: "تسعة"
};
Tafgeet.prototype.teens = {
_11: "أحد عشر",
_12: "أثني عشر",
_13: "ثلاثة عشر",
_14: "أربعة عشر",
_15: "خمسة عشر",
_16: "ستة عشر",
_17: "سبعة عشر",
_18: "ثمانية عشر",
_19: "تسعة عشر"
};
Tafgeet.prototype.tens = {
_10: "عشرة",
_20: "عشرون",
_30: "ثلاثون",
_40: "أربعون",
_50: "خمسون",
_60: "ستون",
_70: "سبعون",
_80: "ثمانون",
_90: "تسعون"
};
Tafgeet.prototype.hundreds = {
_100: "مائة",
_200: "مائتين",
_300: "ثلاثمائة",
_400: "أربعمائة",
_500: "خمسمائة",
_600: "ستمائة",
_700: "سبعمائة",
_800: "ثمانمائة",
_900: "تسعمائة"
};
Tafgeet.prototype.thousands = {
singular: "ألف",
binary: "ألفين",
plural: "ألآف"
};
Tafgeet.prototype.milions = {
singular: "مليون",
binary: "مليونين",
plural: "ملايين"
};
Tafgeet.prototype.bilions = {
singular: "مليار",
binary: "مليارين",
plural: "مليارات"
};
Tafgeet.prototype.trilions = {
singular: "ترليون",
binary: "ترليونين",
plural: "ترليونات"
};
Tafgeet.prototype.columns = ["trilions", "bilions", "milions", "thousands"];
Tafgeet.prototype.currencies = {
SDG: {
singular: "جنيه سوداني",
plural: "جنيهات سودانية",
fraction: "قرش",
fractions: "قروش"
},
SAR: {
singular: "ريال سعودي",
plural: "ريالات سعودية",
fraction: "هللة",
fractions: "هللات"
},
QAR: {
singular: "ريال قطري",
plural: "ريالات قطرية",
fraction: "درهم",
fractions: "دراهم"
},
AED: {
singular: "درهم أماراتي",
plural: "دراهم أماراتية",
fraction: "فلس",
fractions: "فلوس"
},
EGP: {
singular: "جنيه مصري",
plural: "جنيهات مصرية",
fraction: "قرش",
fractions: "قروش"
},
USD: {
singular: "دولار أمريكي",
plural: "دولارات أمريكية",
fraction: "سنت",
fractions: "سنتات"
},
AUD: {
singular: "دولار أسترالي",
plural: "دولارات أسترالية",
fraction: "سنت",
fractions: "سنتات"
},
TND: {
singular: "دينار تونسي",
plural: "دنانير تونسية",
fraction: "مليم",
fractions: "مليمات"
}
};
module.exports = Tafgeet;
Thanks.
Change this:
this.fraction = "" + trimmed[0] + trimmed[1];
To this:
this.fraction = "" + trimmed[0] + trimmed[1] + trimmed[2];
But this is a crude solution you need to do some validations and checks before you deploy this to production

True/false as strings, only allowed boolen

function start() {
var arrNums = [18,23,20,17,21,18,22,19,18,20];
var lowValue, highValue, index, count;
lowValue = Number(document.getElementById("lowValue").value);
highValue = Number(document.getElementById("highValue").value);
index = 0;
count = 0;
document.getElementById("msg").innerHTML+="The values in the array are: ";
while(index < arrNums.length) {
document.getElementById("msg").innerHTML+= arrNums[index] + " ";
index++;
}
index = 0;
if(validateLowAndHigh(lowValue, highValue) == "true") {
while(index < arrNums.length) {
if(arrNums[index] >= lowValue && arrNums[index] <= highValue) {
count++;
}
index++;
}
document.getElementById("msg").innerHTML+= "<br/> There are " + count + " values that exist in this range";
}
}
function validateLowAndHigh(low, high) {
if(low <= high) {
return("true");
} else {
document.getElementById("msg").innerHTML+= "<br/> Low value must be less than or equal to the high vaules";
return("false");
}
}
function clearOutput() {
document.getElementById("msg").innerHTML=" ";
}
I was told that I am not allowed to use true/false as strings, only as boolean. How do I go about fixing this? I am not sure how this works, thank you for the help.
Change your code as like this
Change return true instead of return ("true") or ("false")
And change if (validateLowAndHigh(lowValue, highValue)) instead of if (validateLowAndHigh(lowValue, highValue) == 'true')
function start() {
var arrNums = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var lowValue, highValue, index, count;
lowValue = Number(document.getElementById("lowValue").value);
highValue = Number(document.getElementById("highValue").value);
index = 0;
count = 0;
document.getElementById("msg").innerHTML += "The values in the array are: ";
while (index < arrNums.length) {
document.getElementById("msg").innerHTML += arrNums[index] + " ";
index++;
}
index = 0;
if (validateLowAndHigh(lowValue, highValue)) {
while (index < arrNums.length) {
if (arrNums[index] >= lowValue && arrNums[index] <= highValue) {
count++;
}
index++;
}
document.getElementById("msg").innerHTML += "<br/> There are " + count + " values that exist in this range";
}
}
function validateLowAndHigh(low, high) {
if (low <= high) {
return true;
} else {
document.getElementById("msg").innerHTML += "<br/> Low value must be less than or equal to the high vaules";
return false;
}
}
function clearOutput() {
document.getElementById("msg").innerHTML = " ";
}
Instead of using return("true") and return("false"), use return true and return false
Also, replace if(validateLowAndHigh(lowValue, highValue) == "true") with
if(validateLowAndHigh(lowValue, highValue))
OR
if(validateLowAndHigh(lowValue, highValue) == true)

Difficulty assigning a Discount

As the title says, I'm having trouble assigning discounts to my products. When I load the page it says nan and undefined. Any help is appreciated. Thankyou!
This is my JavaScript code:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
function calculate() {
ProductType = prompt("Please enter the type of product you require!").toUpperCase();
document.write("<br>");
ProductQty = prompt("Please enter the number of products you require!");
elsestatement();
ProductQty = parseInt(ProductQty);
document.write("Type of Products:" + ProductType);
document.write("<br>");
document.write("Number of Products:" + ProductQty);
document.write("<br>");
var GrossAmount =(ProductPrice) * (ProductQty);
document.write("Gross Amount is:" + GrossAmount);
GrossAmount = parseInt(GrossAmount);
discountAmt();
var DiscountAmount = (GrossAmount) - (GrossAmount) * (DiscountPercent)
var TotalAmount = (GrossAmount) * (DiscountPercent)
document.write("<br>");
document.write("Discount Amount:" + DiscountAmount)
document.write("<br>");
document.write("Discount Percent:" + DiscountPercent)
document.write("<br>");
document.write("Total Amount:" + TotalAmount)
}
function elsestatement(){
if (ProductType == 'A') {
ProductPrice = 100;
} else if (ProductType == 'B') {
ProductPrice = 75;
} else if (ProductType == 'C'){
ProductPrice = 50;
}
else {
document.write("<br>");
document.write("Invalid Product Type");
document.write("<br>");
}
if (ProductQty <1|| ProductQty >100) {
document.write("Invalid Quantity")
}
}
function discountAmt() {
if (GrossAmount <200) {
DiscountPercent = '0';
} else if (GrossAmount >= 200 && GrossAmount<=399.99) {
DiscountPercent = '.05';
} else if (GrossAmount>=400 && GrossAmount<=599.99 ) {
DiscountPercent = '.075';
} else if (GrossAmount >=600)
DiscountPercent = '.1';
}
This is my HTML Code:
<!DOCTYPE html>
<html>
<title>Product</title>
<body>
<h1>Product Calc</h1>
<script src="Product.js"> </script>
<script>calculate()</script>
<script>elsestatement()</script>
<script>discountAmt()</script>
</body>
Sorry for the confusion. I was mistaken about the unclosed function. Instead, the problem is that GrossAmount was defined in the calculate function instead of in the outer scope. Therefor, it was not reachable in the discountAmt function.
Here is your fixed code, except with the document.writes removed so that it can run in the sandbox:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
var GrossAmount;
function calculate() {
ProductType = prompt("Please enter the type of product you require!").toUpperCase();
ProductQty = prompt("Please enter the number of products you require!");
elsestatement();
ProductQty = parseInt(ProductQty);
GrossAmount = ProductPrice * ProductQty;
GrossAmount = parseInt(GrossAmount);
discountAmt();
var DiscountAmount = GrossAmount - GrossAmount * DiscountPercent;
var TotalAmount = GrossAmount * DiscountPercent;
}
function elsestatement(){
if (ProductType == 'A') {
ProductPrice = 100;
} else if (ProductType == 'B') {
ProductPrice = 75;
} else if (ProductType == 'C'){
ProductPrice = 50;
} else {}
if (ProductQty < 1|| ProductQty > 100) {}
console.log('ProductPrice: ', ProductPrice);
}
function discountAmt() {
if (GrossAmount < 200) {
DiscountPercent = '0';
} else if (GrossAmount >= 200 && GrossAmount <= 399.99) {
DiscountPercent = '.05';
} else if (GrossAmount >= 400 && GrossAmount <= 599.99) {
DiscountPercent = '.075';
} else if (GrossAmount >= 600) {
DiscountPercent = '.1';
}
console.log('DiscountPercent: ', DiscountPercent);
}
calculate();
Obviously you are not closing the elsestatement function ie } is missing. and manage the code like this
change
<!DOCTYPE html>
<html>
<title>Product</title>
<body>
<h1>Product Calc</h1>
<script src="Product.js"> </script>
<script>calculate()</script>
<script>elsestatement()</script>
<script>discountAmt()</script>
</body>
to
<!DOCTYPE html>
<html>
<title>Product</title>
<script src="Product.js"> </script>
<body>
<h1>Product Calc</h1>
</body>
<script>
$(function(){
calculate();
});
</script>

Categories

Resources