|
| 1 | +const penceString = "399p"; |
| 2 | + |
| 3 | +const penceStringWithoutTrailingP = penceString.substring( |
| 4 | + 0, |
| 5 | + penceString.length - 1, |
| 6 | +); |
| 7 | + |
| 8 | +const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 9 | +const pounds = paddedPenceNumberString.substring( |
| 10 | + 0, |
| 11 | + paddedPenceNumberString.length - 2, |
| 12 | +); |
| 13 | + |
| 14 | +const pence = paddedPenceNumberString.substring( |
| 15 | + paddedPenceNumberString.length - 2, |
| 16 | +); |
| 17 | + |
| 18 | +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" |
| 28 | + |
| 29 | +// Answers |
| 30 | + |
| 31 | +// 2. const penceStringWithoutTrailingP = penceString.substring(0, penceString.length - 1): |
| 32 | +// the substring() method returns the characters starting at index 0(3) up to and excluding the end(9) of penString variable. |
| 33 | +// This way only 399 is extracted of the string. Then the result is assigned to penceStringWithoutTrailingP variable. |
| 34 | + |
| 35 | +// 3. const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"): |
| 36 | +// The method padStart(3, "0") adds the string 0 before if the length of penceStringWithoutTrailingP string is less than 3 characters. |
| 37 | +// It then assign it to paddedPenceNumberString variable. For example if the string is 11, it returns 011 or the string is 1, it returns 001. |
| 38 | + |
| 39 | +// 4. const pounds = paddedPenceNumberString.substring(0, paddedPenceNumberString.length - 2) |
| 40 | +// Again the method substring() returns the characters starting at length 0 and removing the last two characters which are the pence(00). |
| 41 | +// This gives us only the pounds value and it the assigned to the pounds variable. |
| 42 | + |
| 43 | +// 5. const pence = paddedPenceNumberString.substring(paddedPenceNumberString.length - 2).padEnd(2, "0"): |
| 44 | +// substring method first returns the last two characters of the paddedPenceNumberString string. |
| 45 | +// Then the padEnd() method adds a 0 if the length of the string is less than 2. Then it assigns it to pence variable. |
| 46 | + |
| 47 | +// 6. console.log(`£${pounds}.${pence}`): |
| 48 | +// Finally console.log prints the pounds and pence adding the the pound sign £ first using template literal as £3.99 |
0 commit comments