Reputation: 3
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.
Upvotes: 0
Views: 154
Reputation: 412
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
Upvotes: 1
Reputation: 5828
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).
Upvotes: 1