Skip to content

Instantly share code, notes, and snippets.

@pete-murphy
Last active November 27, 2017 20:56
Show Gist options
  • Save pete-murphy/0f284acbc3bfc0cd2833185b58b37a2d to your computer and use it in GitHub Desktop.
Save pete-murphy/0f284acbc3bfc0cd2833185b58b37a2d to your computer and use it in GitHub Desktop.
BofA Money Input: Parse & Format Functions
const format = num =>
(num / 100).toLocaleString("en-US", { style: "currency", currency: "USD" })
const parse = str => +str.replace(/[^0-9.]/, "") * 100
const rEFormat = num => {
const formattedNum =
num.toString().length < 3
? `000${num.toString()}`.slice(-3)
: num.toString()
return `$${formattedNum
.replace(/([0-9]{2})$/, ".$1")
.replace(/\B(?=(\d{3})+(?=\.))/g, ",")}`
}
const rEParse = str => +str.replace(/[^0-9]/g, "").replace(/^0*(\d+)/, "$1")
const tests = [
{ input: 0, expects: "$0.00" },
{ input: 3, expects: "$0.03" },
{ input: 30, expects: "$0.30" },
{ input: 300, expects: "$3.00" },
{ input: 300000, expects: "$3,000.00" }
]
const handle = num => rEFormat(num)
const render = str => rEParse(str)
tests.forEach(test =>
console.log(
test.expects === handle(test.input) && test.input === render(test.expects)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment