4

I've tried casting to float and number_format but float will always round at two and number_format is fixed on the amount of decimals you specify.

So how can I do this like the following conversion

11.2200 -> 11.22
11.2000 -> 11.20
11.2340 -> 11.234
1

4 Answers 4

1
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"

This might help, You can use sprintf given by PHP.

Sign up to request clarification or add additional context in comments.

1 Comment

This will round the number to the nearest decimal, I don't want that.
0

You can use float casting

echo (float) 11.2200;
echo "<br/>";
echo (float) 11.2000;
echo "<br/>";
echo (float) 11.2340;

and you have to check number of digits after decimal point and than get value like below :

$val=(float) 11.2000;
if(strlen(substr(strrchr($val, "."), 1))<2){
    echo number_format($val,2);
} 

2 Comments

echo (float) 11.2000 will return 11.2 not 11.20
I tried this but the problem is that the second one will return 11.2 instead of 11.20
0

You may use the round() function for this.

i-e round(number,precision,mode);

Example:

echo(round(11.2200,2));

Output

11.22

Thanks

8 Comments

Rounding 11.2340 to 2 decimal places will give 11.23 not 11.234
Like Peter said this doesn't return the desired value
@PeterFeatherstone If you use Round function and set the precision it will round of the amount and give you the amount according to the precision you set. 11.2200 when use with round(11.2200,2) will output the 11.22 as it will first round of it then will set the precision
Yes, therefore it is not dynamic. I believe Bart wants it to be dynamic...?
Yes, it can either be 10.12 or 10.123 but not lower than 2 decimals
|
0

Not sure if you need a fix for this anymore, but I just ran into the same problem and here's my solution:

$array = array(11.2200, 11.2000, 11.2340);
foreach($array as $x)
{
    // CAST THE PRICE TO A FLOAT TO GET RID OF THE TRAILING ZEROS
    $x = (float)$x

    // EXPLODE THE PRICE ON THE DECIMAL (IF IT EXISTS)
    $pieces = explode('.',$x);

    // IF A SECOND PIECE EXISTS, THAT MEANS THE FLOAT HAS AT LEAST ONE DECIMAL PLACE
    if(isset($pieces[1]))
    {
        // IF THE SECOND PIECE ONLY HAS ONE DIGIT, ADD A TRAILING ZERO TO FORMAT THE CURRENCY
        if(strlen($pieces[1]) == 1)
        {
            $x .= '0';
        }
    }
    // IF NO SECOND PIECE EXISTS, ADD A .00 TO IT TO FORMAT THE CURRENCY VALUE
    else
    {
        $x .= '.00';
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.