MB.
MB.

Reputation: 723

How to Present a floating point number using php

I have a price database that stores numbers as floating point. These are presented on a website. Prices can be in the format.

x.x    (e.g. 1.4)  
x.xx   (e.g. 1.99)  
x.xxx  (e.g. 1.299) <-- new price format

I used to use the string format or %.2f to standardize the prices to two decimal places but now I need to show 3 as well but only if the price is 3 decimal place long.

e.g.   1.4  would display  1.40
       1.45 would display  1.45
       1.445 would display 1.445

The above formats would be the desired output for the given input.

using %.3f shows all with 3 digits.

e.g.   1.4  would display  1.400     
       1.45 would display  1.450    
       1.445 would display 1.445  

But that is not what i want does anyone know the best way to do the following.

i.e. any number should display 2 decimal places if it has 0 1 or 2 decimal places if it has 3 or more decimal places it should display 3 decimal places

Upvotes: 0

Views: 608

Answers (3)

MB.
MB.

Reputation: 723

Here is what I did due to the need to cope with some special cases I had in the app.

  1. count the number of dec places ($prices is a float from the database).
  2. format based on the count in the places using a switch statement.
  3. For all cases with less than 3 decimal places format with 2 (except zero)
  4. For all other case format with 3.

    $decimals = strlen(substr(strrchr($price,"."),1));  
    switch ($decimals) {
        case 0: {
           if ($price != 0) {
               $price = number_format($price),2);
           }
           break;
        }
        case 1: {
    
           $price = number_format($price),2);
           break;
        }
        case 2: {
    
           $price = number_format($price),2);
           break;
        }
        default: {
           $price = number_format($price),3);    // three dec places all other prices
           break;
        }
    

    }

Thanks for the help...

Upvotes: 0

rich remer
rich remer

Reputation: 3577

I would just format it to three places, then trim a final 0.

$formatted = number_format($value, 3, ".", "");
if (substr($formatted, -1) === "0") $formatted = substr($formatted, 0, -1);

Upvotes: 1

isogram
isogram

Reputation: 21

Use this dude

number_format($data->price, 0, ',', '.');

http://php.net/manual/en/function.number-format.php

Upvotes: 0

Related Questions