Use decimal in quantity fields in WooCommerce – WordPress

As standard WooCommerce does not allow to use decimal values in the quantity field, so we can only add 1, 2, 3, ... and so on to the cart. We had a project, where we would change that, so we came up with a really simple fix.

The fix

In the functions.php theme file, we just added a few lines.

// Add min value to the quantity field (default = 1)
add_filter('woocommerce_quantity_input_min', 'min_decimal');
function min_decimal($val) {
	return 0.1;
}

// Add step value to the quantity field (default = 1)
add_filter('woocommerce_quantity_input_step', 'nsk_allow_decimal');
function nsk_allow_decimal($val) {
	return 0.1;
}

// Removes the WooCommerce filter, that is validating the quantity to be an int
remove_filter('woocommerce_stock_amount', 'intval');

// Add a filter, that validates the quantity to be a float
add_filter('woocommerce_stock_amount', 'floatval');

// Add unit price fix when showing the unit price on processed orders
add_filter('woocommerce_order_amount_item_total', 'unit_price_fix', 10, 5);
function unit_price_fix($price, $order, $item, $inc_tax = false, $round = true) {
	$qty = (!empty($item['qty']) && $item['qty'] != 0) ? $item['qty'] : 1;
	if($inc_tax) {
 		$price = ($item['line_total'] + $item['line_tax']) / $qty;
 	} else {
 		$price = $item['line_total'] / $qty;
	}
 	$price = $round ? round( $price, 2 ) : $price;
 	return $price;
}

This is a really simple solution.

Get it as plugin

We have created a plugin for WordPress and WooCommerce with this feature. With the plugin, you can control the quantity fields per product, per category or for the whole site.

Get the WooCommerce Advanced Quantity plugin on envato.

ms@morningtrain.dk'

Martin Schadegg Rasch Jensen

  • I have searched, tested, trialled and failed a number of other suggestions online. You’re not kidding when you say this a “really simple fix”. This is great. Thank you!

  • I am glad, the fix was useful. 🙂

  • Great snippet 😉 I’m now trying to execute those filters only on a specific product (or category), any clue about this? 🙂

    • You can do something like:
      add_filter(‘woocommerce_quantity_input_min’, ‘min_decimal’, 10, 2);
      function min_decimal($val, WC_Product $product) {
      if(get_the_category($product->id) == 12) { // 12 = ID on the category you want it to work with
      return 0.1;
      }
      return 1;
      }
      add_filter(‘woocommerce_quantity_input_step’, ‘step_decimal’, 10, 2);
      function step_decimal($val, WC_Product $product) {
      if(get_the_category($product->id) == 12) { // 12 = ID on the category you want it to work with
      return 0.1;
      }
      return 1;
      }

      I have not testet it, but I hope i will lead you in the right direction! 🙂

      • Amadeusz Mad

        Hello Martin, could you check this snipped with product category id? Unfortunatly it doesn’t work.

    • I have just created a plugin, where it can be controlled for specific products or categories. I will put it on Envato in near future – but let me know if you want to buy it before, because I do not know when I get the time to put it on Envato.

    • The plugin we have created, where you can control the quantity fields per product and per category is now published. Find it on Envato: http://codecanyon.net/item/woocommerce-advanced-quantity/11861326?ref=MorningTrain

  • Teresa

    Hello
    There is a problem with the unit price in the page order and too in the invoice.
    When the quantity is decimal, the unit price takes the same value as the quantity in decimal.

    wordpress 4.2.2
    woocommerce 2.3.9

    • Is it a problem in the checkoutflow too?
      What plugin, do you use to generate PDF invoices?
      And can you explain what you mean by the page order?

      • Teresa

        Thanks for your answer,

        1º .- Is it a problem in the checkout flow too? … the checkout does the calculation well, the problem is in the unit price in the detail of the orders page when the decimal number is less than 1. The unit price takes the same value as the quantity in decimal.

        2º .- What plugin, do you use to generate PDF invoices? … PDF Invoices https://wordpress.org/plugins/woocommerce-pdf-invoices/
        .- But If I turn off the PDF invoices plugin, the problem persists

        3º .- And can you explain what you mean by the page order? … WooCommerce list of orders (when someone sends a purchase)

        The problem with the UNIT PRICE is when the quantity is less than 1, the unit price takes the same value as the quantity in decimal.
        If the quantity is greater than 1, although the quantity of product has decimals, the unit price appears correct

        I am using this feature to allow dot or comma in the prices
        function site_woocommerce_get_price($price, $product) {
        $decimal_sep = wp_specialchars_decode(stripslashes(get_option(‘woocommerce_price_decimal_sep’)), ENT_QUOTES);
        if ($decimal_sep != ‘.’)
        $price = str_replace($decimal_sep, ‘.’, $price);
        return $price;
        }
        add_filter(‘woocommerce_get_price’, ‘site_woocommerce_get_price’, 10, 2);

        I hope I explained (sorry for my English I’m Spanish)

        • I found out why the problem exists. Try to add this code to the functions.php file:

          public function unit_price_fix($price, $order, $item, $inc_tax = false, $round = true) {
          $qty = (!empty($item[‘qty’]) && $item[‘qty’] != 0) ? $item[‘qty’] : 1;
          if($inc_tax) {
          $price = ($item[‘line_total’] + $item[‘line_tax’]) / $qty;
          } else {
          $price = $item[‘line_total’] / $qty;
          }
          $price = $round ? round( $price, 2 ) : $price;
          return $price;
          }
          add_filter(‘woocommerce_order_amount_item_total’, ‘unit_price_fix’, 10, 5);

          I have not tested the function, but I hope it will work. Please tell me, if this fix the problem, so I can add it to the articel 🙂

          • Teresa

            If add this code in the file function.php the page is blank
            I still have no knowledge to understand the code

            thanks anyway

          • Okay, when I get some time, I will test it on my own site, and then reply with a solution.

          • I have updated the article with the fix for this problem.

          • Teresa

            Ok, now it works perfectly, and also with the invoice PDF plugin
            Many thanks for the script
            This code should be included in the code of WooCommerce.
            I am developing an online fruit shop and is very useful in this case. Can see huverfruit.es

            Regards

          • I’m glad I could help. If you need more control, you can control it per product, per category and for the whole site, with the new plugin we just released. Find it on Envato: http://codecanyon.net/item/woocommerce-advanced-quantity/11861326?ref=MorningTrain

          • Teresa

            Hello again,
            I found another bug in the rate of VAT, directly related when the quantity is less than 1.
            Iva rate is multiplied by the quantity of product when the quantity is less than 1.
            For example, if the quantity is 0.5, the VAT rate of 4% is listed on the invoices as 2%. If the quantity is 0.8, the rate of VAT appears as 3.2% etc.

            The result in the total price is fine, but the rate of VAT appears wrong
            I’m using the plugin WooCommerce Jetpack http://woojetpack.com/shortcodes/wcj_order_items_table/
            and the problem is with the shortcode line_tax_percent

            Good plugin Advanced Quantity
            Regards

          • function unit_price_fix($price, $order, $item, $inc_tax = false, $round = true) {

            $qty = (!empty($item[‘qty’]) && $item[‘qty’] != 0) ? $item[‘qty’] : 1;

            if($inc_tax) {

            $price = ($item[‘line_total’] + $item[‘line_tax’]) / $qty;

            } else {

            $price = $item[‘line_total’] / $qty;

            }

            $price = $round ? round( $price, 2 ) : $price;

            return $price;

            }

            add_filter(‘woocommerce_order_amount_item_total’, ‘unit_price_fix’, 10, 5);

            This code works.

  • We have created a plugin, where you can control the quantity fields per product, per category and for the whole site. Find it on Envato: http://codecanyon.net/item/woocommerce-advanced-quantity/11861326?ref=MorningTrain

  • Aaron McKeehan

    ….In the functions.php theme file which is where? I have 5 different function.php files 🙁

    • Aaron McKeehan

      Nevermind, thank you! This worked!

  • Thomas Scherner

    Hallo and Thanks i had a Problem on he First Part it show min 1 but i want 0,5 for Start buying. Can you help please

    // Add min value to the quantity field (default = 1)

    add_filter(‘woocommerce_quantity_input_min’, ‘min_decimal’);

    function min_decimal($val) {

    return 0.5;

    }

  • Hayley

    Hi there – Any chance you have a suggestion for how to make this plugin work on the product archives page aswell? It works perfectly on my single product page but I’d love to allow customers to buy without having to enter the single product page (I’m also doing a veggie delivery shop).

  • priyanka choudhary

    Hi Martin,
    It’s working perfectly on my website. Thank you so much for your great help. Love you!

  • מרכז הפרח

    Dose it possible to make all this solution for a group of item by some tag ?

  • Gil shasha

    I want to contain the this specific function only for a Group of products which have a specific tag.
    Is it possible?
    thanks for the help!

  • chen c

    Advanced Quantity plugin can support WooCommerce 3.3.1?

  • is it possible to allow also values from smaller than 1 on the product page. As it is now you can only do that from the cart, after you added an item with qty bigger than 1 . I

    • Maybe it is yor theme, that overwrites the input fields arguments the wrong way? Because it should apply to the product page as well. What theme do you use?

  • Phong Mai

    Hi, this code is working fine with inputs of values buy decimal but how can I still keep the increments by 1 instead of ie. 0.1. At the same time user can input manual values by decimal?

  • Euan Fielder

    How can we use this code to allow for decimals on minimum order value?

    Any advise greatly appreciated.

  • Edson Ferreira

    many many many thanks!

  • Alfonso

    Hola, funciona con la ultima actualización de woocommerce? He visto varios plugin que están fallando

  • JC

    Is there a way to only set this for one category of products and set specific quantity intervals? For example, 1, 2.5, 5, 7.5.

  • Mafe Kstano

    Thank you, I was looking for this for a long time!!!!!!!! <3 I just add this to set the min and max value:

    // Maximum and minimum value
    add_filter( 'woocommerce_available_variation', 'jk_woocommerce_available_variation' ); // Variations

    function jk_woocommerce_available_variation( $args ) {
    $args['max_qty'] = 100; // Maximum value (variations)
    $args['min_qty'] = 0.5; // Minimum value (variations)
    return $args;
    }

  • Marcelo Guerra

    there is a problem.

    product is $ 10
    qty is 1.75
    – the total to pay in the cart is $ 17.5

    When I want to show in the cart that the payment is for 1.75, its OK!

    But…
    $ cart_item [‘quantity’] returns 1

    OR
    If instead of being 1.75 it is 0.75 it returns 0
    OR…
    If it is 20.77, it returns 20

    —– The decimal fraction is lost. ——

    Also, if we use WC duplicate order

    Maintains the final price of $ 17.50

    change the qty from 1.75 to 1

    in the order, for the product, change the unit price from $ 10 to $ 17.50

    Any idea ?

    Saludos.

  • PanDi Kumar . K

    I need a help,

    How can i set float value to “Low stock threshold” in Product inventory tab.

    Thanks for advance https://uploads.disquscdn.com/images/4a3edfa1dbacc2a57076b514ff99f6e8e47077f814fc51ab3c7199ac2e6bad9f.png

  • vikash chaudhary

    brother i need help
    i want to take order in 2 decimal places like 1.25, 1.75, 2.25 etc
    please help me

  • Edson Kuhn

    Hi,

    Is there a possibility to the product not show the decimal? only back end?
    Thanks in advance.
    Edson