Javascript - 2 statements for one condition - javascript

I'm trying to allow my prices to display under 2 conditions
sales price must be less than the base price
"don't show pricing is unchecked" (yes or no) in our system
var basPrc = "$5000";
var onlnPrc = "<%=getAttribute('item','382798','salesprice')%>";
var CallForPrice = "<%=getAttribute('item','382798','dontshowprice')%>";
if (onlnPrc < basPrc || CallForPrice == "No") {
document.write('<span class="strike">Base Price: <span>'+basPrc+'</span></span>')
document.write("<br /><strong class=\"saleprice\">Our Price: <%=getAttribute('item','382798','salesprice')%></strong><br />");
//savings
var savings = onlnPrc - basPrc;
document.write ('<span class="save">You Save: <span class="red">'+ savings +'</span></span><br />');
}
//if don't show pricing is checked
if (CallForPrice = "Yes") {
var basPrc = null;
var onlnPrc = null;
document.write('<br /><strong class="saleprice">Call For Pricing<strong><br />');
}
//if no online pricing
else {document.write('<br /><strong class="saleprice">Our Price: '+basPrc+' <strong><br />');}
I tried the "&&" operators and no luck, any idea on what I should do next?

Your basPrc is a String, not a Number; you should initialize it to 5000, not "$5000" (the lack of quotes being important here). I'm not sure at all what onlnPrc will be. You need to make sure both are numbers. Otherwise, when you do basPrc > onlnPrc you will be doing a String comparison, not a numeric one.
// Base Price defaults to 5000
var basPrc = 5000;
// Parse the Online Price as a floating point number;
// if the result is NaN, default it to 0
var onlnPrc = parseFloat("<%=getAttribute('item','382798','salesprice')%>") || 0;
You should endeavor to make sure that basPrc and onlnPrc are always numbers since you are doing calculations with them. Leave the display of currency symbols or decimal points to the pieces of the code where you actually display the data.
Unrelated question: Where does this code live? What's it for? I've never seen NetSuite code that looked anything like this.

Related

Trying to make a language translation app

I am trying to make a translation app that can translate a number between 1-30 from english to its german/french counterpart. I think I am somewhat on the right track, ive made the arrays with all the translations, but the problems I am having is I don't know how to correlate the number the user puts in via a prompt, to one of the values in the array, example:
User is prompted for number between 1-30, user is prompted for language French/German = Translation
This is what I am trying to do. Bellow is what I have so far, feel free to nit pick, but bear in mind I am new to Javascript so there is probably a lot wrong.
function translate() {
if (lang = "French") {
console.log(frenchTranslation);
} else {
console.log(germanTranslation);
}
};
var x=translate
translate(x)
var number=(Number(prompt ("What is your number? Must be between 1-30")));
var lang=(prompt ("What is your language? Must be 'French' or 'German'. Case Sensitive."));
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
Right, so first of all, you need to add some input validation to know what the user has selected. I recommend storing it somewhere, then you should make sure that it's in the correct range. Just use an if statement to check if the number is >= 0 && <= 30. After that when you're trying to use console.log you need to use array index of the correct number.
Here's my solution, you can improve on it a lot.
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
function translate()
{
const yournumber = Number(prompt("Enter your number (1-30)"));
console.log(yournumber);
const language = prompt("Choose a language - German or French");
if(yournumber < 1 || yournumber > 30) {
alert("Too hard");
}
else {
if(language === "French") {
console.log(frenchTranslation[yournumber]);
}
if(language === "German") {
console.log(germanTranslation[yournumber]);
}
}
}
translate();

Show the average of the 1-digit numbers entered

I have a problem with the following exercise:
Enter N number of numbers by prompt. Show the average of the 1-digit numbers entered. End the program with the word “exit"/"salir”.
I also have to do the average calculation with a function. Here's what I have:
let i;
var sum = 0;
var avg = 0;
var average = function(i) {
sum = sum + i;
avg = sum/(i+1);
}
do {
i = prompt("Ingrese un numero: ");
if ((i < 10) && (i > -10)) {
average(i);
}
} while (i !== "salir");
alert(`el promedio de los numeros de un solo digito es: ${avg}`);
I tried limiting the program by stating that the average function will only be executed for one digit numbers, but the problem is that this is giving me the total average of all the numbers entered not the average of only the 1 digit numbers.
You've succeeded in avoiding including multi-digit numbers from the sum and average. The problem isn't in that, it's here:
avg = sum/(i+1);
That's not how averages work. An average is the sum divided by how many values went into making that sum. (The number of numbers you added to sum.)
Keep track of how many numbers you added to sum, and use that count to calculate the average.
Side note: A couple of notes on the code, just for what they're worth:
Your code is currently relying on implicit conversion from string (what the user types in) to number (what you use with sum). Although it works in this example, I strongly recommend doing the conversion explicitly. My other answer here (also on SO) lists your various options for doing that.
You've used both let and var in your code. I suggest never using var, it has no place anymore in modern JavaScript. Use let if you need to let the variable's value change (as with sum), and const when you don't.
You're missing one ; (after the assignment statement assigning to average). (You can rely on Automatic Semicolon Insertion if you like [I don't recommend relying on it, but some others do], but whichever way you go, it's best to know the rules and then consistently do or don't include your ;.)
I suggest declaring your variables in the innermost scope you can declare them in. There's no reason for i to be global in your code, just make it local to the do-while loop body.
Obviously in a very simple exercise like this it's mostly fine, but I recommend not getting used to prompt and alert, they're relics from the 1990s and behave in very unusual (and sometimes problematic) ways compared to most functions in JavaScript.
var i;
var sum = 0;
var avg = 0;
var average = function(num) {
sum = sum + num;
i+=1
avg = sum/i;
}
var ans;
do {
ans = prompt("Ingrese un numero: ");
if ((ans < 10) && (ans > -10)) {
average(ans);
}
} while (ans !== "salir");
alert(`el promedio de los numeros de un solo digito es: ${avg}`);
Should remove this but will leave it here for any future visitors.

jQuery Conditional Decimal Greater Than Comparison

I have an odd issue that I'm not sure quite how to fix, but here it goes.
I've got a return from an AJAX query and this is how two parts are returned (and how they look in the preview panel):
id:1
paid: "158.40"
balance: "79.20"
So initially I had just tried the following (after noticing an issue):
if(item.balance > item.paid){
var test = "balance greater than paid";
}else{
var test = "balance is not";
}
But in the above case, it returns the first test meaning that somewhere, the it thinks that 79.20 is greater than 158.40, which is obviously not what I want.
So I tried this:
var paid = parseFloat(item.paid).toFixed(2);
var balance = parseFloat(item.balance).toFixed(2);
And just switch the first line of the above conditional statement to if(balance > paid) and it still did the same thing...
So I am at a loss, if anyone can help - I'd be very appreciative.
Don't use toFixed when comparing those values, because it just gives you another string, which it can't compare numerically in the way you're trying to compare. Just compare the outputs of parseFloat.
var paid = "158.40";
var balance = "79.20";
$(".string").text(paid > balance);
paid = parseFloat("158.40");
balance = parseFloat("79.20");
$(".float").text(paid > balance);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
String compare:
<span class="string">
</span>
</div>
<div>
Float compare:
<span class="float">
</span>
</div>
try to use Number() to convert string to numbers first
if(Number(item.balance) > Number(item.paid)){
var test = "balance greater than paid";
}else{
var test = "balance is not";
}
Use it like below
var paid = parseFloat(item.paid);
var balance = parseFloat(item.balance);
Then compare it will take you into right condition
Above you are using toFixed which again returns string.
Referring to toFixed method, it is returning a String, not a Number. Hence the comparison result is not expected. There is no need to call this method for your case. If you have concern on the precision, take a look on this question
var item = {
id: 1,
paid: "158.40",
balance: "79.20"
};
var paid = parseFloat(item.paid);
var balance = parseFloat(item.balance);
console.log("paid=" + paid);
console.log("balance=" + balance);
console.log("paid>balance=" + (paid > balance));

Trouble with Loop and Functions in Javascript

So i have an assignment and ive been doing it now for a few hours and am very stuck on a few parts of it. So the parts im stuck on is having to use a loop to validate information put into a prompt, and using information from an array to coincide with with a variable in another function and finally displaying all of it.
So I have everything set up but have no idea what exactly im getting wrong here if someone would mind helping point me in the right direction? Oh I should probably mention Im trying to get the second function to go with the array so when the user enters a number (1 through 4) it matches with the prices in the array.
function numSeats() {
//var amountSeat=document.getElementById("price");
var amountSeat=prompt("Enter the amount of seats you would like");
amountSeat=parseInt(amountSeat);
for (i=7; i<amountSeat; i++){
if (amountSeat<1 || amountSeat>6) {
alert("Check the value of " + amountSeat);
location.reload(true);
}else{
alert("Thank You");}
}
return amountSeat;}
function seatingChoice() {
//var seatChoice=document.getElementById("table").innerHTML;
var seatChoice=prompt("Enter the seat location you want.");
seatChoice=parseInt(seatChoice);
for (i=7; i<seatChoice; i++){
if (seatChoice<1 || seatChoice>4) {
alert("Check what you entered for " + seatChoice);
location.reload(true);
}else{
alert("Thank You")}
}
return seatChoice;}
var price=new Array(60, 50, 40, 30);
var name=prompt("Please enter your name.");
if (name==null || name=="")
{
alert("You did not enter a name, try again");
location.reload(true);
}
else
{
alert("Thank You");
}
document.write(name + " ordered " + numSeats() + " for a total dollar amount of " + seatingChoice(
) );
It looks to me like you repeat the same error in both numSeats and seatingChoice;
Let's look at what you're doing with your loop
var amountSeat = prompt("Enter the amount of seats you would like");
for (i=7; i<amountSeat.length; i++) {/* amountSeat[i] */}
prompt asks the client for a String, so amountSeat is a String.
amountSeat.length is thus the number of characters in the String.
You start your loop at i = 7, thus amountSeat[i] starts from the 7th character in the amountSeat (assuming there are at least 7 characters in amountSeat)
It looks to me more like you want to get a number from the prompt;
// string
var amountSeat = prompt("Enter the amount of seats you would like");
// to number
amountSeat = parseInt(amountSeat, 10); // radix of 10 for base-10 input
Next, consider your if
if (amountSeat[i]<1 && amountSeat[i]>6) {
This is saying if less than 1 AND more than 6. No number can be both of these states at the same time, so it will always be false. It looks like you wanted to use an OR, ||
// do your check
if (amountSeat < 1 || amountSeat > 6) { /* .. */ }
Finally, it looks like you want to calculate the price by some logic, which you haven't included. However, I'm sure it will be based upon numSeats and seatingChoice so you will need to keep a reference to these choices.

How to trim zero's from price in Magento 1.7.0.2 (JavaScript)

Here is the code:
function wpTrimZeroRight(price, precision) {
var format = {
'pattern': '%s',
'precision': precision,
'requiredPrecision': precision,
'decimalSymbol': '.',
'groupSymbol': '',
'groupLength': 0,
'integerRequired': 2
};
var xPrice = formatCurrency(price, format);
var decimal = '';
var pointPos = xPrice.lastIndexOf('.');
if (pointPos !== -1) decimal = xPrice.substr(pointPos);
var c1 = decimal.length;
decimal = decimal.replace(new RegExp("[0]+$", "g"), "");
var c2 = decimal.length;
var xPrecision = precision - (c1 - c2);
return xPrecision;
This piece of code is taken from webandpeople trim price extension. It does the job but in configurable and bundle producs trim all zeros; so when the price looks like £11.50 on the category page on product page looks like £11.5 . The idea is to have two decimal numbers everywhere except where products cost £0.012 for example. I have played with the code a bit and I changed (new RegExp("[0]+$", "g"), ""); to (new RegExp("00", "g"), "0") This gives me £28.990 on some products but the correct amount of £55.50 on the others. I think there is lack of if statement but nothing with much sense comes to my mind. I already spent few hours searching for the answer here and on the other magento related sites. I would be grateful for any ideas.
Javascript Number.toFixed method is what you are lookign for. (12.5001).toFixed(2) --> 12.50
Why you need to trim a price. I think magento automatically does it.
Use code like Mage::helper('core')->currency($price, true, false);
wherever you are getting price. I think you would get the price in formatted manner

Categories

Resources