|
4 | 4 | // You will need to declare a function called toPounds with an appropriately named parameter. |
5 | 5 |
|
6 | 6 | // You should call this function a number of times to check it works for different inputs |
| 7 | + |
| 8 | +function toPounds(penceString) { |
| 9 | + const penceStringWithoutTrailingP = penceString.substring( |
| 10 | + 0, |
| 11 | + penceString.length - 1 |
| 12 | + ); |
| 13 | + |
| 14 | + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 15 | + const pounds = paddedPenceNumberString.substring( |
| 16 | + 0, |
| 17 | + paddedPenceNumberString.length - 2 |
| 18 | + ); |
| 19 | + |
| 20 | + const pence = paddedPenceNumberString |
| 21 | + .substring(paddedPenceNumberString.length - 2) |
| 22 | + .padEnd(2, "0"); |
| 23 | + |
| 24 | + return `£${pounds}.${pence}`; |
| 25 | +} |
| 26 | + |
| 27 | +console.log(toPounds("399p")); |
| 28 | + |
| 29 | +const actualOutput = toPounds("4685p"); |
| 30 | +const expectedOutput = "£46.85"; |
| 31 | + |
| 32 | +console.assert( |
| 33 | + actualOutput === expectedOutput, |
| 34 | + `expected to get ${expectedOutput}, but got ${actualOutput}` |
| 35 | +); |
| 36 | + |
| 37 | +const actualOutput1 = toPounds("123456p"); |
| 38 | +const expectedOutput1 = "£1234.56"; |
| 39 | + |
| 40 | +console.assert( |
| 41 | + actualOutput1 === expectedOutput1, |
| 42 | + `expected to get ${expectedOutput1}, but got ${actualOutput1}` |
| 43 | +); |
| 44 | + |
| 45 | +const actualOutput2 = toPounds("4p"); |
| 46 | +const expectedOutput2 = "£0.04"; |
| 47 | + |
| 48 | +console.assert( |
| 49 | + actualOutput2 === expectedOutput2, |
| 50 | + `expected to get ${expectedOutput2}, but got ${actualOutput2}` |
| 51 | +); |
0 commit comments