|
1 | 1 | const penceString = "399p"; |
| 2 | +// Declares constant variable named penceString and assigns the string 399p |
| 3 | +// This indicates price in pence |
2 | 4 |
|
3 | 5 | const penceStringWithoutTrailingP = penceString.substring( |
4 | 6 | 0, |
5 | 7 | penceString.length - 1 |
6 | 8 | ); |
| 9 | +// Constant variable is declared to remove the trailing p in 399p to just keep the numeric part |
| 10 | +// penceString.length is number of characters in 399p = 4 so -1 is 3 |
| 11 | +// substring(0, 3) returns the characters from index 0 up to index 3 exclusive, returning 399. |
7 | 12 |
|
8 | 13 | const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 14 | +// padStart ensures that the string has at least 3 characters by adding leading zeros if necessary |
| 15 | +// This standardises the numeric string to simplify splitting into pounds and pence. |
| 16 | +// In this case, 399 already has 3 characters, so no padding is added. |
| 17 | + |
9 | 18 | const pounds = paddedPenceNumberString.substring( |
10 | 19 | 0, |
11 | 20 | paddedPenceNumberString.length - 2 |
12 | 21 | ); |
| 22 | +// The last two characters represent pence |
| 23 | +// Const pounds is declared as a variable consisting of a substring of previously declared variable and a newly calculated variable |
| 24 | +// paddedPenceNumberString.length computes index where last two characters start, so that is after 1 character. |
| 25 | +// substring(0, 1) extracts the pounds part, by returning the characters from index 0 up to index 1 exclusive. |
| 26 | +// This is "3" in this case. |
13 | 27 |
|
14 | | -const pence = paddedPenceNumberString |
15 | | - .substring(paddedPenceNumberString.length - 2) |
16 | | - .padEnd(2, "0"); |
| 28 | +const pence = paddedPenceNumberString |
| 29 | +// New variable to ensure two-digit pence component is formatted correctly. |
| 30 | + .substring(paddedPenceNumberString.length - 2) |
| 31 | + // returns substring from index to the end inclusive |
| 32 | + // For 399, start index is character 1 (the first 9) so this returns 99. |
| 33 | + .padEnd(2, "0"); |
| 34 | + // Ensures pence string has at least 2 characters by adding trailing zeros if needed |
| 35 | + // So 5p would become 005 and this would return 05. |
17 | 36 |
|
18 | 37 | console.log(`£${pounds}.${pence}`); |
| 38 | +// Template string that joins pounds and pence parts with a decimal point and logs it |
| 39 | +// This displays the standard and prints it to the console. |
19 | 40 |
|
20 | 41 | // This program takes a string representing a price in pence |
21 | 42 | // The program then builds up a string representing the price in pounds |
|
0 commit comments