Skip to content

Instantly share code, notes, and snippets.

@christianberkman
Last active October 19, 2022 19:39
Show Gist options
  • Save christianberkman/91a7e946db6802099af9b9df40b89f06 to your computer and use it in GitHub Desktop.
Save christianberkman/91a7e946db6802099af9b9df40b89f06 to your computer and use it in GitHub Desktop.
Create float from unkown currency amount in unkown format
/*
This function will take (almost) any string representing a monetary amount and parse it correctly as a float.
Thousand seperator can be '.' or ','
Decimal point can be '.' or ','
Currency symbols etc. will be removed
The following strings will all parse to (float) 1250.99:
1250.99
1,250.99
1.250,99
€1.250,99
$1.250,99
Ush 1,250.99/=
Etc.
The following strings will all parse to (float/int) 10500:
10500.00
10,500
10.500
10500
Etc.
@param mixed amount Amount to parse
@return float
*/
function amountToFloat(amount){
// Return amount if already a number float
if(typeof(amount) == 'number') return amount;
// Remove all characters except numbers, '.' and ','
let amountStr = amount.toString()
const cleanStr = amountStr.replace(/[^0-9.,]/g, '')
// Search for decimal point in cleanStr
const decimalPoint = cleanStr.charAt( cleanStr.length - 3)
// Extract only integers from cleanStr
const amountInt = parseInt( cleanStr.replace(/[^0-9]/g, '') )
// Create float from amountInt
let amountFloat
// Decimal Point found
if(decimalPoint == ',' || decimalPoint == '.'){
// Divide by 100 cents to make float
amountFloat = parseFloat( amountInt / 100)
}
// Decimal point not found
else{
// Create float from amountInt
amountFloat = parseFloat(amountInt)
}
return amountFloat
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment