|
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 | +function toPounds(penceString) { |
| 8 | + const penceStringWithoutTrailingP = penceString.substring( |
| 9 | + 0, |
| 10 | + penceString.length - 1 |
| 11 | + ); //variable |
| 12 | + // "penceStringWithoutTrailingP" declared and assigned first three characters |
| 13 | + // of "penceString" using the substring method, removing the trailing "p". |
| 14 | + |
| 15 | + const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 16 | + // variable "paddedPenceNumberString" declared and assigned the value of "penceStringWithoutTrailingP" |
| 17 | + // padded to a minimum length of 3 characters with leading zeros using the padStart method. Which is clever way, |
| 18 | + // really to replace it with zeros if number of pence is less than 3 characters long. |
| 19 | + |
| 20 | + const pounds = paddedPenceNumberString.substring( |
| 21 | + 0, |
| 22 | + paddedPenceNumberString.length - 2 |
| 23 | + ); |
| 24 | + //Variable "pounds" declared and assigned value of "paddedPenceNumberString" but without the last |
| 25 | + // two characters. |
| 26 | + |
| 27 | + const pence = paddedPenceNumberString |
| 28 | + .substring(paddedPenceNumberString.length - 2) |
| 29 | + .padEnd(2, "0"); |
| 30 | + // Variable "pence" declared and assigned value of the last two characters of "paddedPenceNumberString" |
| 31 | + // and padded to a minimum length of 2 characters with zeros at the end, padEnd method is used once again. |
| 32 | + // it is to ensure that if the number of pence is less than 2 characters long, it will be padded with zeros |
| 33 | + // at the end. |
| 34 | + |
| 35 | + return `£${pounds}.${pence}`; |
| 36 | + // Finally equivalent in "pounds" and "pence" is returned |
| 37 | +} |
| 38 | +console.log(toPounds("2345")); // testing with normal string of numbers |
| 39 | +console.log(toPounds("-2345")); // testing with string of negative numbers |
| 40 | +console.log(toPounds("0")); // testing with zero |
0 commit comments