|
1 | 1 | const penceString = "399p"; |
| 2 | +// 1. Initializes a string variable with the value "399p" representing the price in pence with a trailing 'p'. |
2 | 3 |
|
3 | 4 | const penceStringWithoutTrailingP = penceString.substring( |
4 | 5 | 0, |
5 | 6 | penceString.length - 1 |
6 | 7 | ); |
| 8 | +// 2. Removes the trailing 'p' by taking a substring from index 0 up to (but not including) the last character. |
| 9 | +// Result: "399" |
7 | 10 |
|
8 | 11 | const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 12 | +// 3. Ensures the string is at least 3 characters long by padding with leading zeros if needed. |
| 13 | +// In this case, "399" is already 3 characters, so it remains "399". |
| 14 | + |
9 | 15 | const pounds = paddedPenceNumberString.substring( |
10 | 16 | 0, |
11 | 17 | paddedPenceNumberString.length - 2 |
12 | 18 | ); |
| 19 | +// 4. Extracts the pounds part by taking all characters except the last two. |
| 20 | +// For "399", this is "3" (the hundreds place). |
13 | 21 |
|
14 | 22 | const pence = paddedPenceNumberString |
15 | 23 | .substring(paddedPenceNumberString.length - 2) |
16 | 24 | .padEnd(2, "0"); |
| 25 | +// 5. Extracts the last two characters as the pence part. |
| 26 | +// For "399", this is "99". |
| 27 | +// Then pads the string on the right with zeros if it’s shorter than 2 characters (not needed here). |
17 | 28 |
|
18 | 29 | console.log(`£${pounds}.${pence}`); |
19 | | - |
20 | | -// This program takes a string representing a price in pence |
21 | | -// The program then builds up a string representing the price in pounds |
22 | | - |
23 | | -// You need to do a step-by-step breakdown of each line in this program |
24 | | -// Try and describe the purpose / rationale behind each step |
25 | | - |
26 | | -// To begin, we can start with |
27 | | -// 1. const penceString = "399p": initialises a string variable with the value "399p" |
| 30 | +// 6. Prints the formatted price string with a £ sign, pounds, and pence separated by a dot. |
| 31 | +// Output: "£3.99" |
0 commit comments