|
| 1 | +//initialises a string variable with the value "399p" |
1 | 2 | const penceString = "399p"; |
2 | 3 |
|
| 4 | +//creates a substring of penceString to remove the trailing or the last character p value and |
| 5 | +//assign the new value to "penceStringWithoutTrailingP" |
3 | 6 | const penceStringWithoutTrailingP = penceString.substring( |
4 | 7 | 0, |
5 | 8 | penceString.length - 1 |
6 | | -); |
| 9 | +); //it will save 399 in penceStringWithoutTrailingP |
| 10 | + |
| 11 | +/* The method padStart is used when we want our string to have at least some length; |
| 12 | + in this case if the length of our string is less than 3, we are going to put "0" |
| 13 | + in extra spaces |
| 14 | + The reason for padding the pence number string to 3 size is because in the next step |
| 15 | + we will create a substring by removing the last two values |
| 16 | + and that will give us the pounds number value and the remaining characters will be the |
| 17 | + pence value. */ |
| 18 | +const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); //it will not change our string because 399 already has three characters |
7 | 19 |
|
8 | | -const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0"); |
| 20 | +/* Here we are trying to get the pounds value out of the total pence value |
| 21 | + Therefore we are creating a substring of paddedPenceNumberString to |
| 22 | + create a string that removes the last two numbers from paddedPenceNumberString |
| 23 | + which are pence numbers. */ |
9 | 24 | const pounds = paddedPenceNumberString.substring( |
10 | 25 | 0, |
11 | 26 | paddedPenceNumberString.length - 2 |
12 | 27 | ); |
13 | 28 |
|
| 29 | + |
| 30 | +/* Here, we are doing two things: |
| 31 | + 1. we are creating a substring of paddedPenceNumberString |
| 32 | + to get the pence numbers only by returning the last two numbers. |
| 33 | + 2. We are using padEnd method to pad our result to two character values |
| 34 | + and adding 0 at the end if the length of our substring is less than 2 |
| 35 | + |
| 36 | + Note: However, our paddedPenceNumberString length is always going to be at least 3 |
| 37 | + and the below substring is going to return us the last two characters which is pence value |
| 38 | + So, I don't understand the use padEnd and in fact, I tried commenting it and tested the code |
| 39 | + with different penceString values and the results are same. */ |
14 | 40 | const pence = paddedPenceNumberString |
15 | 41 | .substring(paddedPenceNumberString.length - 2) |
16 | 42 | .padEnd(2, "0"); |
17 | | - |
| 43 | + |
| 44 | +// in the below code we are printing the value starting with £ symbol of pounds and pence separated by "." |
18 | 45 | console.log(`£${pounds}.${pence}`); |
19 | 46 |
|
20 | 47 | // This program takes a string representing a price in pence |
|
0 commit comments