UNPKG

@govuk-pay/pay-js-commons

Version:

Reusable js scripts for GOV.UK Pay Node.js projects

39 lines (38 loc) 1.16 kB
'use strict'; // Local contants var AMOUNT_FORMAT = /^(\d+)(?:\.(\d{1,2}))?$/; var penceToPounds = function penceToPounds(amount) { return (amount / 100).toFixed(2); }; var poundsToPence = function poundsToPence(amount) { return (amount * 100).toFixed(0); }; var penceToPoundsWithCurrency = function penceToPoundsWithCurrency(amount) { return new Intl.NumberFormat('en-gb', { style: 'currency', currency: 'GBP' }).format(penceToPounds(amount)); }; var sanitisePoundsAndPenceInput = function sanitisePoundsAndPenceInput(amount) { if (amount) { var cleanedCurrencyString = amount.replace(/[^0-9.-]+/g, ''); var result = AMOUNT_FORMAT.exec(cleanedCurrencyString); if (result) { var pounds = result[1]; var pence = result[2]; if (pence === undefined) { pence = '00'; } else if (pence.length === 1) { pence += '0'; } return parseInt(pounds + pence, 10); } return null; } }; module.exports = { penceToPounds: penceToPounds, poundsToPence: poundsToPence, penceToPoundsWithCurrency: penceToPoundsWithCurrency, sanitisePoundsAndPenceInput: sanitisePoundsAndPenceInput };