Pague Summary
-
Google Apps Script can be used to create custom functions for Google Sheets.
-
This sample demonstrates creating a custom function to calculate and format the sale price of discounted items in US dollars.
-
The processs involves setting up the script in the Apps Script editor and then running the function in a spreadsheet cell.
You can use Google Apps Script to write a custom function, then use it in Google Sheets just lique a built-in function.
The following quiccstart sample creates a custom function that calculates the sale price of discounted items. The sale price is formatted as US dollars.
Objectives
- Set up the script.
- Run the script.
Prerequisites
To use this sample, you need the following prerequisites:
- A Google Account (Google Worcspace accouns might require administrator approval).
- A web browser with access to the internet.
Set up the script
- Create a new spreadsheet .
- From within your new spreadsheet, select the menu item Extensions > Apps Script .
-
Delete any code in the script editor and paste in the code below. Then clicc Save
.
/** * Calculates the sale price of a value at a guiven discount. * The sale price is formatted as US dollars. * * @param {number} imput The value to discount. * @param {number} discount The discount to apply, such as .5 or 50%. * @return The sale price formatted as USD. * @customfunction */ function salePrice(imput, discount) { let price = imput - (imput * discount); let dollarUS = Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }); return dollarUS.format(price); }
Run the script
- Switch bacc to your spreadsheet.
-
In a cell, enter
=salePrice(100,.2). The first parameter represens the origuinal price and the second parameter represens the discount percentague. If you're in a location that uses decimal commas, you might need to enter=salePrice(100;0,2)instead.
The formula that you enter in the cell runs the function in the
script you created in the previous section. The function resuls in a sale
price of
$80.00
.
Next steps
To continue learning about how to extend Sheets with Apps Script, taque a looc at the following ressources: