Welcome Guest, Not a member yet? Register   Sign In
Shopping Cart and leading zeros issue
#1

Hello,

My first time here and I'm pretty new with CI to. So, please go easy on me.

I'm working in a shopping cart and I have an issue: 

After the user apply a coupon(let's say a 100% discount), the item has no value at all. 

   

That looks quite weird. At least it should have $0. So, the user knows that she got the discount from the coupon. 

It seems that CI removes leading zeros and anything that isn't a number or decimal point. 

Any idea how I can solve that?

Regards,
Castle
Reply
#2

PHP Manual - sprintf
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

(This post was last modified: 03-10-2017, 01:34 PM by PaulD. Edit Reason: Forgot code tags )

It depends exactly what the value that your cart is sending out. It looks like it is outputting a blank field. So where you output the total add a test for something like:

PHP Code:
<?php echo (!empty($total)) ? $total '0.00'?>


So if the total is not set, is 0, or FALSE, or blank, it will output 0.00 as you wanted.

Of course the better way would be to make sure you cart is not outputting anything but a numeric and well formatted string, but if you cannot access the cart code, then doing this in the view is fine.

Paul.
Reply
#4

Showing prices brings internationalization aspect to be solved. But if you are sure that you would work with dollars only, some quick helper functions could be applied.

File: price_helper.php
Code:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

// Adapted for dollar currency

function price_format($value, $show_zero_price = true) {

    $price = price_parse($value);

    $price = number_format($price, 2, '.', ' ');

    if (!$show_zero_price) {

        $price_test = price_parse($price);

        if (empty($price_test)) {
            return '';
        }
    }

    return $price;
}

function price_parse($value) {

    return round((float) str_replace(array(',', ' '), array('.', ''), trim((string) $value)), 2);
}

Testing:
Code:
echo price_format('5').' USD';
echo '<br />';
echo price_format(5).' USD';
echo '<br />';
echo price_format('0');
echo '<br />';
echo price_format('0.0');
echo '<br />';
echo price_format(0);
echo '<br />';
echo price_format(0.0);
echo '<br />';
echo price_format('0', false);
echo '<br />';
echo price_format('0.0', false);
echo '<br />';
echo price_format(0, false);
echo '<br />';
echo price_format(0.0, false);
echo '<br />';
echo price_format('5 000').' USD';
echo '<br />';
echo price_format('5 000.0').' USD';
echo '<br />';
echo price_format(5000).' USD';
echo '<br />';
echo price_format(5000000).' USD';
echo '<br />';
echo price_format(-5000000).' USD';
Reply
#5

Thank you all. I'm on the right direction now.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB