Parse a string into a number in PHP

/**
 * Simple way to parse a string to PHP number.
 */
function parse_string_to_php_number( $number_string ) {
	if ( false !== strpos( $number_string, '.' ) ) {
		// a) correct decimal number - no changes, e.g.: 2.45
		// b) with comma as thousands separator, e.g.: 1,200.45 -> 1200.45
		return str_replace( ',', '', $number_string );
	} else {
		// a) integer - no changes, e.g.: 2
		// b) with comma as decimal separator, e.g.: 1200,45 -> 1200.45
		return str_replace( ',', '.', $number_string );
	}
}

No comments yet.

Leave a Reply