0

I've got a problem with quantity rounding. I set a step to 0.1 and after adding quantity at some point instead of getting 0.8 it's 0.7999999 and I honestly don't know how to fix it. Here's code in function.php I've used (created by LoicTheAztec):

// custom conditional function (check for product categories)
function enabled_decimal_quantities( $product ){
    $targeted_terms = array(77, 72, 71, 65, 62, 61, 118, 117, 89, 93, 120, 81, 83, 63, 80, 68, 98, 69, 84, 119, 78, 127, 79, 82, 70, 73, 88, 155, 146, 140, 220); // Here define your product category terms (names, slugs ord Ids)

    return has_term( $targeted_terms, 'product_cat', $product->get_id() );
}

// Defined quantity arguments 
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 9000, 2 );
function custom_quantity_input_args( $args, $product ) {
    if( enabled_decimal_quantities( $product ) ) {
        if( ! is_cart() ) {
            $args['input_value'] = 0.5; // Starting value
        }
        $args['min_value']   = 0.5; // Minimum value
        $args['step']        = 0.5; // Quantity steps
    }
    return $args;
}

// For Ajax add to cart button (define the min value)
add_filter( 'woocommerce_loop_add_to_cart_args', 'custom_loop_add_to_cart_quantity_arg', 10, 2 );
function custom_loop_add_to_cart_quantity_arg( $args, $product ) {
    if( enabled_decimal_quantities( $product ) ) {
        $args['quantity'] = 0.5; // Min value
    }
    return $args;
}

// For product variations (define the min value)
add_filter( 'woocommerce_available_variation', 'filter_wc_available_variation_price_html', 10, 3);
function filter_wc_available_variation_price_html( $data, $product, $variation ) {
    if( enabled_decimal_quantities( $product ) ) {
        $data['min_qty'] = 0.5;
    }
    return $data;
}

// Enable decimal quantities for stock (in frontend and backend)
remove_filter('woocommerce_stock_amount', 'intval');
add_filter('woocommerce_stock_amount', 'floatval');



add_filter( 'woocommerce_quantity_input_step', 'filter_woocommerce_quantity_input_step', 10, 2 );
function filter_woocommerce_quantity_input_step($arg, $product) {

    if( enabled_decimal_quantities( $product ) ) {
    $arg = 0.5;}
    else {
        $arg = 1;   
    }
    
    return $arg; 
}; 

Any help much appreciated.

Mat
  • 1
  • 1
  • 1
    Does this answer your question? [Why not use Double or Float to represent currency?](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency) – Oleg Ushakov May 18 '22 at 08:31

0 Answers0