Skip to content

Commit 13ffd18

Browse files
committed
Implement toPounds function to convert pence to pounds and add test cases
1 parent 183aa5b commit 13ffd18

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,31 @@
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+
// normalize input to a trimmed string
10+
const input = String(penceString).trim();
11+
12+
// remove trailing 'p' if present
13+
const numericPart = input.endsWith('p') ? input.slice(0, -1) : input;
14+
15+
// ensure at least 3 digits so we can safely split into pounds / last two pence
16+
const padded = numericPart.padStart(3, '0');
17+
18+
// all but the last two digits are pounds
19+
const pounds = padded.slice(0, padded.length - 2);
20+
21+
// last two digits are pence; ensure two chars
22+
const pence = padded.slice(-2).padEnd(2, '0');
23+
24+
return ${pounds}.${pence}`;
25+
}
26+
27+
// Test calls
28+
console.log(toPounds("399p")); // £3.99
29+
console.log(toPounds("5p")); // £0.05
30+
console.log(toPounds("75p")); // £0.75
31+
console.log(toPounds("0p")); // £0.00
32+
console.log(toPounds("1234p")); // £12.34
33+
console.log(toPounds(" 42p ")); // £0.42 (works with extra whitespace)
34+
console.log(toPounds("500")); // £5.00 (works without trailing 'p')

0 commit comments

Comments
 (0)