skip to Main Content

How could I change the NaN text to 0?

Im using a function to show a variable price calculator in a Woocommerce store.

Until some variable are selected Im getting a NaN result, once selected it works fine so I would like to just change the NaN text to zero.

This is the code:

// hook this on priority 31, display below add to cart button.
add_action( 'woocommerce_single_product_summary', 'woocommerce_total_product_variation_price', 31 );
function woocommerce_total_product_variation_price() {
global $woocommerce, $product;
// setup base html... We are going to rewrite this with the standard selected variation
echo sprintf('<div id="product_total_price" style="margin-bottom:20px; display: block;">%s %s</div>',__('Precio Total:','woocommerce'),'<span class="price">'.$product->get_price().'</span>');
?>
    <script>
        jQuery(function($){

        var currency    = currency = ' <?php echo get_woocommerce_currency_symbol(); ?>';

            function priceformat() {
                var product_total = parseFloat(jQuery('.woocommerce-variation-price .amount').text().replace(/ /g ,'').replace(/€/g ,'').replace(/,/g ,'.')) * parseFloat(jQuery('.qty').val());
                var product_total2 = product_total.toFixed(2);
                var product_total3 = product_total2.toString().replace(/./g, ',');

                jQuery('#product_total_price .price').html( currency + ' ' + product_total3);
            }

            jQuery('[name=quantity]').change(function(){
                priceformat();
            });

            jQuery('body').on('change','.variations select',function(){
                priceformat();              
            });

            priceformat();

        });
    </script>
<?php }

Thanks in advance

2

Answers


  1. Just check if the variable is NaN and if it is set it to zero.

    if(isNaN(product_total)){
        product_total = 0
    }
    
    Login or Signup to reply.
  2. A simpler way to do this is:

    product_total = product_total || 0
    

    Because product_total is NaN it will assign it to 0. Be careful though because 0 is also considered a falsey value in this scenario.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search