Skip to content

Instantly share code, notes, and snippets.

@mbijon
Created March 17, 2012 01:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbijon/2054126 to your computer and use it in GitHub Desktop.
Save mbijon/2054126 to your computer and use it in GitHub Desktop.
Human-format currency $'s converted to machine floating points
<?php
/*
* Human-format currency $'s converted to machine floating points
*/
// Dollar amount via GET (not very secure)
$raw_dollar_amount = ( isset($_GET['dollar_amount']) ) ? htmlentities( $_GET['dollar_amount'], ENT_QUOTES, 'UTF-8' ) : FALSE;
if ( $raw_dollar_amount ) {
// Create a return value in case nothing done
$float_dollar_amount = $raw_dollar_amount;
// Build string of only the separators
$separators_only = preg_filter( '/[^,\.]/i', '', $raw_dollar_amount );
/*
*
* Check # of separators
* If more than one, position determines region
*
* NOTE: Am assuming no separators in the decimal portion
* That could be problem for complex #'s, but this isn't physics class after all
*
*/
if ( strlen( $separators_only ) > 1 ) {
if ( substr( $separators_only, 0, 1) == '.' ) {
$float_dollar_amount = str_replace( '.', '', $float_dollar_amount );
$float_dollar_amount = str_replace( ',', '.', $float_dollar_amount );
} else if ( substr( $separators_only, 0, 1) == ',' ) {
$float_dollar_amount = str_replace( ',', '', $float_dollar_amount );
}
} else if ( strlen( $separators_only ) == 1 && $separators_only == ',' ) {
/*
* Here's the crux assumption made for fule prices:
* That "4.99", "4.9999" or "4,999" is likely to be float "4.9{999}"
*
* Other option is to measure # digits after the separator
* ...but then we hit same problem as prev regex:
* http://www.php.net/manual/en/function.floatval.php#85346
*
*/
$float_dollar_amount = str_replace( ',', '.', $float_dollar_amount );
}
// Output trackers & processed value
echo "<h2>Raw &amp; Filtered Values</h2>";
echo "Float $-value: $float_dollar_amount<br /><br />";
echo "Raw input $-value: $raw_dollar_amount<br />";
echo "Separators from raw input: $separators_only<br /><br />";
}
// Input form
?>
<h2>Input a $-amount here</h2>
<form id="dollar_input" name="dollar_input" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" name="dollar_amount" />
<input type="submit" value="Submit" />
</form>
@mbijon
Copy link
Author

mbijon commented Mar 19, 2012

Understood. I might have added different parsing code for each number type, but I saw your comment about 1,200 lines ... a lot for a plugin to track fuel & mileage.

@Viper007Bond
Copy link

I'm up past 1800 lines now. I expect to pass 2000 before the plugin gets released. Lots of fancy features. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment