Skip to content

Commit c1b8638

Browse files
committed
3-to-pounds.js committed
1 parent e27fa7b commit c1b8638

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,41 @@
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+
9+
// REUSABLE FUNCTION SOLUTION:
10+
11+
function toPounds(penceString) {
12+
// Remove the trailing 'p' character
13+
const penceStringWithoutTrailingPound = penceString.substring(
14+
0,
15+
penceString.length - 1
16+
);
17+
18+
// Pad with leading zeros to ensure at least 3 characters
19+
const paddedPenceNumberString = penceStringWithoutTrailingPound.padStart(3, "0");
20+
21+
// Extract pounds (all except last 2 digits)
22+
const pounds = paddedPenceNumberString.substring(
23+
0,
24+
paddedPenceNumberString.length - 2
25+
);
26+
27+
// Extract pence (last 2 digits) and ensure it's 2 digits
28+
const pence = paddedPenceNumberString
29+
.substring(paddedPenceNumberString.length - 2)
30+
.padEnd(2, "0");
31+
32+
// Return the formatted string
33+
return ${pounds}.${pence}`;
34+
}
35+
36+
// TEST THE FUNCTION:
37+
38+
console.log(toPounds("399p")); // £3.99
39+
console.log(toPounds("99p")); // £0.99
40+
console.log(toPounds("5p")); // £0.05
41+
console.log(toPounds("1000p")); // £10.00
42+
console.log(toPounds("12345p")); // £123.45
43+
console.log(toPounds("0p")); // £0.00
44+

0 commit comments

Comments
 (0)