|
1 | 1 | // In Sprint-1, there is a program written in 3-mandatory-interpret/3-to-pounds.js |
2 | 2 |
|
3 | 3 | // You will need to take this code and turn it into a reusable block of code. |
| 4 | + |
| 5 | +const penceString = "399p"; |
| 6 | + |
| 7 | +const penceStringWithoutTrailingP = penceString.substring( |
| 8 | + 0, |
| 9 | + penceString.length - 1 |
| 10 | +); |
| 11 | + |
| 12 | +const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 13 | +const pounds = paddedPenceNumberString.substring( |
| 14 | + 0, |
| 15 | + paddedPenceNumberString.length - 2 |
| 16 | +); |
| 17 | + |
| 18 | +const pence = paddedPenceNumberString |
| 19 | + .substring(paddedPenceNumberString.length - 2) |
| 20 | + .padEnd(2, "0"); |
| 21 | + |
| 22 | +console.log(`£${pounds}.${pence}`); |
| 23 | + |
| 24 | + |
4 | 25 | // You will need to declare a function called toPounds with an appropriately named parameter. |
5 | 26 |
|
| 27 | +function toPounds(penceString) { |
| 28 | + const penceStringWithoutTrailingP = penceString.substring( |
| 29 | + 0, |
| 30 | + penceString.length - 1 |
| 31 | + ); |
| 32 | + |
| 33 | + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 34 | + const pounds = paddedPenceNumberString.substring( |
| 35 | + 0, |
| 36 | + paddedPenceNumberString.length - 2 |
| 37 | + ); |
| 38 | + |
| 39 | + const pence = paddedPenceNumberString |
| 40 | + .substring(paddedPenceNumberString.length - 2) |
| 41 | + .padEnd(2, "0"); |
| 42 | + |
| 43 | + return `£${pounds}.${pence}`; |
| 44 | +} |
| 45 | + |
6 | 46 | // You should call this function a number of times to check it works for different inputs |
| 47 | + |
| 48 | +console.log(toPounds("399p")); // Output: £3.99 |
| 49 | +console.log(toPounds("5p")); // Output: £0.05 |
| 50 | +console.log(toPounds("1234p")); // Output: £12.34 |
| 51 | +console.log(toPounds("0p")); // Output: £0.00 |
| 52 | + |
| 53 | + |
0 commit comments