Skip to content

Commit 3fee2c5

Browse files
committed
Implement toPounds function to convert pence to formatted pounds and add test cases
1 parent 99dad40 commit 3fee2c5

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,36 @@
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+
// 1. Remove the trailing 'p'
10+
const penceStringWithoutTrailingP = penceString.substring(
11+
0,
12+
penceString.length - 1
13+
);
14+
15+
// 2. Pad with zeros to ensure we always have at least 3 digits (e.g., "5" becomes "005")
16+
const paddedPenceNumberString = penceStringWithoutTrailingP.padStart(3, "0");
17+
18+
// 3. Extract the pounds (everything except the last two digits)
19+
const pounds = paddedPenceNumberString.substring(
20+
0,
21+
paddedPenceNumberString.length - 2
22+
);
23+
24+
// 4. Extract the pence (just the last two digits)
25+
const pence = paddedPenceNumberString
26+
.substring(paddedPenceNumberString.length - 2)
27+
.padEnd(2, "0");
28+
29+
// 5. Return the formatted currency string
30+
return ${pounds}.${pence}`;
31+
}
32+
33+
// --- Test Cases ---
34+
// Calling the function multiple times to check it works for different inputs
35+
console.log(toPounds("399p")); // Expected output: "£3.99"
36+
console.log(toPounds("5p")); // Expected output: "£0.05"
37+
console.log(toPounds("2500p")); // Expected output: "£25.00"
38+
console.log(toPounds("99p")); // Expected output: "£0.99"
39+
console.log(toPounds("10000p")); // Expected output: "£100.00"

0 commit comments

Comments
 (0)