wc_format_decimal

Format decimal numbers ready for DB storage.

Description

(string) wc_format_decimal( (number) $number, (constant) $dp = false, (bool) $trim_zeros = false ); 

Sanitize, remove locale formatting, and optionally round + trim off zeros.

Returns (string)

Parameters (3)

0. $number (number)
Expects either a float or a string with a decimal separator only (no thousands)
1. $dp — Optional. (constant) => false
Number of decimal points to use, blank to use woocommerce_price_num_decimals, or false to avoid all rounding.
2. $trim_zeros — Optional. (bool) => false
From end of string

Usage

  1. if ( !function_exists( 'wc_format_decimal' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-formatting-functions.php'; 
  3.  
  4. // Expects either a float or a string with a decimal separator only (no thousands) 
  5. $number = null; 
  6.  
  7. // number of decimal points to use, blank to use woocommerce_price_num_decimals, or false to avoid all rounding. 
  8. $dp = false; 
  9.  
  10. // from end of string 
  11. $trim_zeros = false; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = wc_format_decimal($number, $dp, $trim_zeros); 
  15.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-formatting-functions.php  
  1. function wc_format_decimal( $number, $dp = false, $trim_zeros = false ) { 
  2. $locale = localeconv(); 
  3. $decimals = array( wc_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] ); 
  4.  
  5. // Remove locale from string. 
  6. if ( ! is_float( $number ) ) { 
  7. $number = wc_clean( str_replace( $decimals, '.', $number ) ); 
  8. $number = preg_replace( '/[^0-9\., -]/', '', $number ); 
  9.  
  10. if ( false !== $dp ) { 
  11. $dp = intval( '' == $dp ? wc_get_price_decimals() : $dp ); 
  12. $number = number_format( floatval( $number ), $dp, '.', '' ); 
  13.  
  14. // DP is false - don't use number format, just return a string in our format 
  15. } elseif ( is_float( $number ) ) { 
  16. $number = wc_clean( str_replace( $decimals, '.', strval( $number ) ) ); 
  17.  
  18. if ( $trim_zeros && strstr( $number, '.' ) ) { 
  19. $number = rtrim( rtrim( $number, '0' ), '.' ); 
  20.  
  21. return $number;