Skip to content
Advertisement

Change percentage decimal precision in Woocommerce deposits plugin payment plan

I’m using the Woocommerce Deposits plugin. It uses percentages to calculate the deposit and payment. I need the deposit and payment to be an exact amount. I can calculate the exact percentages to give the exact amount but the plugin does not allow decimal points for the percentages. It rounds up or down to a whole number.

Example: I need 28.3465% it will round down to 28%.

I used the code (below) which allowed me to add 2 decimal places. So 28.3465% would round off to 28.35%. I changed line 133 of class-wc-deposits-plans-admin.php from this:

$plan_amounts = array_map( 'absint', $_POST['plan_amount'] );

to this:

$plan_amounts = array_map( 'wc_format_decimal', $_POST['plan_amount'] );

Is there a function or some way to add 4 decimal points instead of 2?

I found this on woo’s docs, but I can’t figure it out.

https://docs.woocommerce.com/wp-content/images/wc-apidocs/function-wc_format_decimal.html

Thanks in advance

Advertisement

Answer

You need your own custom formatting function based on wc_format_decimal() source code that will handle 4 decimals by default:

function wc_four_decimals( $number, $dp = 4 ) {
    $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 );
        $number = preg_replace( '/[^0-9.,-]/', '', wc_clean( $number ) );
    }

    return number_format( floatval( $number ), $dp, '.', '' );
}

Code goes in function.php file of your active child theme (or active theme, or in a plugin file). Tested and works.

Then you will replace simply:

$plan_amounts = array_map( 'wc_format_decimal', $_POST['plan_amount'] );

by:

$plan_amounts = array_map( 'wc_four_decimals', $_POST['plan_amount'] );

To change the decimal precision programmatically in Woocommerce you can use the following hooked function, where you can add any condition (the default value is set in Woocommerce genera settings):

add_filter( 'wc_get_price_decimals', 'custom_decimals_precision'){
function custom_decimals_precision($dec){
    $dec = 4; // Four decimals precision

    return $dec; 
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement