Skip to content

Commit 7e1a0bf

Browse files
author
russom
committed
A reusable function created from previous sprint.
1 parent dffd727 commit 7e1a0bf

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Sprint-2/3-mandatory-implement/3-to-pounds.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,47 @@
44
// You will need to declare a function called toPounds with an appropriately named parameter.
55

66
// 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+
// p is removed from the string with the sub string method.
11+
0,
12+
penceString.length - 1
13+
// length - 1 is used to get the index of the last character in penceString, which is p.
14+
);
15+
16+
const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
17+
// padStart is used to ensure that the string has at least 3 characters by adding 0 at the start of the string
18+
// if it is less than 3 characters long. This is important for formatting purposes,
19+
// as we want to ensure that we have at least 3 digits to represent pounds and pence.
20+
const pounds = paddedPenceNumberString.substring(
21+
0,
22+
paddedPenceNumberString.length - 2
23+
// substring is used to extract the pounds portion of the string by taking all characters except the last two,
24+
// which represent pence.
25+
);
26+
27+
const pence = paddedPenceNumberString
28+
.substring(paddedPenceNumberString.length - 2)
29+
.padEnd(2, "0");
30+
// substring is used to extract the pence portion of the string by taking the last two characters.
31+
// padEnd is used to ensure that the pence portion has at least 2 characters by adding 0 at the end of the string
32+
// if it is less than 2 characters long. This is important for formatting purposes,
33+
// as we want to ensure that we have at least 2 digits to represent pence.
34+
return ${pounds}.${pence}`;
35+
// finally, the function returns a string representing the price in pounds,
36+
// formatted with a £ symbol and a decimal point separating pounds and pence.
37+
}
38+
console.log(toPounds("399p"));
39+
console.log(toPounds("1p"));
40+
console.log(toPounds("3999p"));
41+
// above are some test cases to check if the function works correctly for different inputs.
42+
43+
// This program takes a string representing a price in pence
44+
// The program then builds up a string representing the price in pounds
45+
46+
// You need to do a step-by-step breakdown of each line in this program
47+
// Try and describe the purpose / rationale behind each step
48+
49+
// To begin, we can start with
50+
// 1. const penceString = "399p": initialises a string variable with the value "399p"

0 commit comments

Comments
 (0)