wc_format_decimal( float|string $number, mixed $dp = false, bool $trim_zeros = false )

Format decimal numbers ready for DB storage.


Description Description

Sanitize, remove decimals, and optionally round + trim off zeros.

This function does not remove thousands – this should be done before passing a value to the function.


Parameters Parameters

$number

(Required) Expects either a float or a string with a decimal separator only (no thousands).

$dp

(Optional) number Number of decimal points to use, blank to use woocommerce_price_num_decimals, or false to avoid all rounding.

Default value: false

$trim_zeros

(Optional) From end of string.

Default value: false


Top ↑

Return Return

(string)


Top ↑

Source Source

File: includes/wc-formatting-functions.php

function wc_format_decimal( $number, $dp = false, $trim_zeros = false ) {
	$locale   = localeconv();
	$decimals = array( wc_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] );

	// Remove locale from string.
	if ( ! is_float( $number ) ) {
		$number = str_replace( $decimals, '.', $number );

		// Convert multiple dots to just one.
		$number = preg_replace( '/\.(?![^.]+$)|[^0-9.-]/', '', wc_clean( $number ) );
	}

	if ( false !== $dp ) {
		$dp     = intval( '' === $dp ? wc_get_price_decimals() : $dp );
		$number = number_format( floatval( $number ), $dp, '.', '' );
	} elseif ( is_float( $number ) ) {
		// DP is false - don't use number format, just return a string using whatever is given. Remove scientific notation using sprintf.
		$number = str_replace( $decimals, '.', sprintf( '%.' . wc_get_rounding_precision() . 'f', $number ) );
		// We already had a float, so trailing zeros are not needed.
		$trim_zeros = true;
	}

	if ( $trim_zeros && strstr( $number, '.' ) ) {
		$number = rtrim( rtrim( $number, '0' ), '.' );
	}

	return $number;
}


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.