Skip to content

Commit 2b518a5

Browse files
committed
Implemented toPounds() function to convert pence strings into pounds.pence format
1 parent 3cd9638 commit 2b518a5

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,26 @@
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+
// Converts a string representing pence (e.g. "399")
9+
// into pounds.pence format (e.g. "3.99")
10+
// MDN References used:
11+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
12+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
13+
14+
// Converts a pence string (e.g. "399")
15+
function toPounds(penceString) {
16+
// Ensure the string is atleast 3 characters long by padding with leading zeros if needed
17+
// e.g. "5" → "005", "99" → "099", "399" stays "399"
18+
const padded = penceString.padStart(3, "0");
19+
// Extract everything except the last two digits → this becomes the pounds
20+
// e.g. "399" → "3"
21+
const pounds = padded.substring(0, padded.length - 2);
22+
// Extract the last two digits → this becomes the pence
23+
// e.g. "399" → "99"
24+
const pence = padded.substring(padded.length - 2);
25+
// Combines pounds and pence into the final money format
26+
return `${pounds}.${pence}`;
27+
}
28+
29+
console.log(toPounds("399")); // 3.99

0 commit comments

Comments
 (0)