Good morning folks. I just started to learn JS and got a task in which I am stuck. I need to change number format to have 2 decimal places and it should also start with pound sign.
function formatCurrency() {
var formated = formated.toFixed(2);
return formated;
}
function calculateSalesTax(price: number) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
When I tried to shorten numbers it throws me an error.Could you please point me in correct direction, as it looks like a very simple task.
Try like this:
function formatCurrency(price) {
var formated = price.toFixed(2);
return formated;
}
function calculateSalesTax(price) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
The formatCurrency function needs to accept an argument (the price) passed into it and use that in the formatting.
The calculateSalesTax function shouldn't have the type definition added to the argument (this is fine in TypeScript).
Here is your correct code:
function formatCurrency(price) {
return `\u00A3 ${price.toFixed(2)}`;
}
function calculateSalesTax(price) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
You were not declaring an argument for formatCurrency. \u00A3 is the code for the pound sign, as putting £ will result in a bad behaviour in js. The backticks (``) allows you to use "literal", go search for it, it is a useful tool in javascript. Also, you attempted to declare a return type for calculateSalexTaxPrice, which you can not since typing is possibile in TypeScript only
Related
I am a beginner, working on a beginner problem but need some help
I am trying to write my own tip calculator app but I result in NaN.
I am sure it is an easy fix but I don't see what the problem is yet. My code is below. Can someone tell me what I am doing wrong that results in my finalCost resulting in NaN instead of billAmount + tipTotal?
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount / 100;
var tipTotal = tip * billAmount;
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost());
So close! You just missed passing the values into your final calculation method.
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount/100;
var tipTotal = tip*billAmount;
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost(billAmount, tipTotal));
You could also remove the parameters and just use the "global" values in calculating
var billAmount = prompt('What is your total bill?');
var tipAmount = prompt('How much do you want to tip');
console.log(billAmount);
var tip = tipAmount/100;
var tipTotal = tip*billAmount;
function finalCost() {
return billAmount + tipTotal;
};
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost());
There's another catch; setting float values directly from a prompt() doesn't ensure float values (treated as string by default), so wrap your prompt() functions in a parseFloat() function:
var billAmount = parseFloat(prompt('What is your total bill?'));
var tipAmount = parseFloat(prompt('How much do you want to tip'));
if(isNaN(billAmount) || isNaN(tipAmount)){
alert("Bill amount or Tip is Invalid");
} else {
console.log("This bill is " + billAmount);
var tip = tipAmount / 100;
var tipTotal = tip * billAmount;
console.log("The tip is " + tipTotal);
console.log("The total bill is " + finalCost(billAmount, tipTotal));
}
function finalCost(billAmount, tipTotal) {
return billAmount + tipTotal;
};
This should validate that billAmount and tipAmount values are floats, and prevent further execution if they aren't.
I am making a food delivery app. I would like that there would be a place whereby it would display the total. Right now, I am unable to display the total amount from multiplying quantity and price. It does not show up on the app.
And, there are no errors on the console too.
Javascript Code:
function _showorderResult(arr) {
var value1 = arr[0].price;
var value2 = arr[0].quantity;
for (var i = 0; i < arr.length; i++) {
result = value1 * value2;
htmlstring = "";
$("#itemimage").html("<img src='" + serverURL() + "/images/" +
arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("result").append(htmlstring);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime)
}
}
And, there are no errors on the console too.
There were plenty of errors in my console, but there are several mistakes here. The first is that your code is not runnable. Please consider making a minimal, verifiable example.
Next, you are misusing or not properly formatting the append(...) function. That's intended to append HTML elements, not string values.
As the comments suggest, you seem to have confused var result and $("result"). If you're not using the DOM selector, you probably don't want to jQuery-wrap your variables. The proper jQuery-wrap syntax would have been $(result) without the double quotes, but please don't do that either, it doesn't offer any benefit over just var result. htmlstring doesn't contain any actual HTML, so I've renamed it runningTotal instead and add it to the price * quantity. This must be initialized first or you'll get NaN.
Make sure to initialize your variables. To this point, there's some hard-coded indexes such as value1 = arr[0].price which make no sense in this pasted code. We can assume you left these here after troubleshooting. Please clean them up next time.
Finally, this is minor, but be consistent with your object names... e.g. imagefile versus imageFile. It doesn't matter which you choose so as long as you're consistent. This will help find typos down the road.
Here's a working example:
<html>
<img src="" id="itemimage">
<p id="price">Price: $0.00</p>
<p id="itemname">Item: None</p>
<p id="quantity">Quantity: None</p>
<p id="result">Running: None</p>
<p id="requestedDateTime">To delivery by: None</p>
<p id="deliveredDateTime">Delivered on: None</p>
<script>
var order = [{
price: 5,
quantity: 3,
itemName: 'Pizza',
imagefile: 'pizza.png',
requestedDateTime: '12:00',
deliveredDateTime: '12:30'
}];
/** Dummy function to allow code to run **/
var serverURL = function() { return ""; }
function _showorderResult(arr) {
// var value1 = arr[0].price;
// var value2 = arr[0].quantity;
var result;
var runningTotal = 0;
for (var i = 0; i < arr.length; i++) {
result = arr[i].price * arr[i].quantity;
runningTotal += result;
$("#itemimage").html("<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("#result").html("Running" + ":" + runningTotal);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime);
}
}
_showorderResult(order);
</script>
</html>
Suceeded in randomizing a quote but now the values name and quote don't match, is there a way to make json.name and json.quote share the same random value? so Einstein's quote isn't matched with the name Nightingale.
let url =;
$.getJSON( url, function( json ) {
let rand = function getRandom() {
return Math.floor(Math.random() * 4) + 1 ;
}
//console.log(rand());
document.write(" "" + json[rand()].quote +""" + " by "
+json[rand()].name );
});
document.write(" "" + json[rand()].quote +""" + " by "
+json[rand()].name );
everytime you use rand(), it will generate a different number, so json[rand()].quote and json[rand()].name will be different because you are using different keys, so save rand() in a variable first and then use it, like:
var randNumber = rand();
document.write(" "" + json[randNumber].quote +""" + " by " +json[randNumber].name );
I have a symbol (#) seperated variable as shown below
var inputStr = "IceCreams#Cone";
How can i split this and form a string in java script variable .
With the above input String how can form a string as
Are You Sure to add a Category Under IceCreams => Cone
I have tried as shown below ,but couldn't achive that dynamically
Thanks in advance .
function myFunction(inputStr)
{
var res = inputStr.split('#');
var r = confirm("Are You Sure to add a Category Under" +res[0]+" "+res[1]+" );
if (r == true) {
} else {
}
}
http://jsfiddle.net/4km0k9nv/1/
You code works if you fix your typo.
window.onload = function() {
function myFunction(inputStr) {
var res = inputStr.split('#');
alert("Are You Sure to add a Category Under " + res[0] + " " + res[1] + " ?" );
}
myFunction("Ice#cream");
}
If you just want to replace the "#" symbol, you can use the string replace function.
var str = "part1#part2";
var str2 = str.replace('#', " => ");
Your example should work fine, but it seems to be a typo.
Good Luck
I was messing around with it and I came up with this. Is this what you want? It runs the function on the input element blur.
function myFunction(inputStr)
{
var res = inputStr.split('#');
confirm("Are You Sure to add a Category Under " + res[0] + " => " + res[1] + " ?");
}
<input type="text" onblur="myFunction(this.value)">
Hope this helps!
function myFunction(inputStr)
{
var res = inputStr.split('#');
var r = confirm("Are You Sure to add a Category Under " + res[0] + " => "+ res[1] + "?");
if (r == true) {
addNewCategory(res[0], res[1]); // rename/rewrite this call as needed
} else {
cancelAdd(); // replace this line with whatever you need.
}
}
Alternatively you can say:
var res = inputStr.replace("#", " => ");
var r = confirm("Are You Sure to add a Category Under " + res + "?");
The second bit of code would make res a string instead of an array of strings. Depending on your needs, that may suffice. If you'd like to or need to use res as an array of strings, then the first chunk of code should be all your need.
I am using prototype in my application but I am not sure how to add this correctly. Basically I have the following function and I need to construct the href of an anchor from which I already have the reference to a series of appended values
MyJavascriptClass.prototype.init = function() {
this.ToDate = $(this.Prefix + 'ToDate');
this.FromDate = $(this.Prefix + 'FromDate');
}
so in the following function I need to add those as parameters in the url attribute
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=7/18/2012&EndDate=1/19/2012');
}
How can i do something like 'MyWebPage.aspx?StartDate=this.ToDate&EndDate=this.FromDate' ? Any help would be appreciated.
If you are using jquery, and $(this.Prefix + 'ToDate') and $(this.Prefix + 'FromDate') represent fields that contain values, then you can do this:
MyJavascriptClass.prototype.btnClicked = function(evt) {
this.lnkShowLink.setAttribute('href', 'MyWebpage.aspx?StartDate=' + this.ToDate.val() + '&EndDate=' + this.FromDate.val() + '');
}
It is difficult to tell from your code what they represent, and why you have them wrapped in $(..).
If ToDate and FromDate contain the two date values, then this should work...
'MyWebPage.aspx?StartDate=' + this.ToDate + '&EndDate=' + this.FromDate
If you don't know every properties:
var properties = [];
for(var i in this)
if(this.hasOwnProperty(i))
properties.push(i+'='+this[i]);
var url = 'MyWebPage.aspx?'+properties.join('&');
var string = "My name is: ",
name = "Bob",
punctuation = ".",
greeting = string + name + punctuation;
Or
var User = { name : "Bob", age : 32, sign : "Leo" },
welcome = "Hi, I'm " + User.name + ", and I'm " + User.age + " years old, I'm a " + User.sign + ", and I enjoy long walks on the beach.";