PHP formatting number, 35 should be 3500 - php

I'm working with currencies and there are some items that cost say $35, some that are $35.50, etc. I'd like to take these numbers and format them to '3500' and if it's 35.50, it should be 3550.
I've tried
number_format($data['amount'], 2, '', '')
But if it's 35.50 it's 355000.
Any help would be great, thanks!

Did you try to multiply the number by 100?

Think of your math lessons:
echo $data['amount'] * 100;

look at the doc, then try this:
number_format($data['amount'], 2)
with those last two '' you were replacing the decimal separator with nothing and the thousands separator with nothing, which is something i don't believe you intended to do.
update
i see from the comments below that i misread your question.
I tried your code with demo here: http://codepad.org/uNAd84gG
and it seems to be in working order.

try:
number_format($amount, 2, ',', '.')
You can omit the last 2 to just have it behave by your locale
number_format($amount, 2);

Related

PHP Round() not working properly

I need help. I'm doing this:
round($myvar,2);
And this is the number I'm getting: 9.779999999999999€
With the other variables it works just fine, any idea how to fix this?
I did this:
<?php echo round(9.7752,2);?>
And I got: 9.779999999999999
I believe it's something in php.ini as #MarkBaker said..
But, I fixed it by doing:
<?php echo number_format($myvar,2);
And I got exactly what I wanted.
Thanks guys for the help!
what problem I encounter is that round(18.203,2) = 18.2 ,then json_encode(...) = 18.199999999 .
so I find the solution is json_encode(strval(round(18.203,2))) = 18.2
it works
Just join empty string before round function like
$val = "" . round(9.597466245, 2);
something (could be in some 3rd party code ?) set your ini setting precision to 16
$php -a
php > echo ini_get("precision");
14 // default
php > echo round(9.7752,2);
9.78
php > echo ini_set("precision", 16);
14
php > echo round(9.7752,2);
9.779999999999999
Although OP solved his issue, I saw this while searching for other (but similar) issue.
If you came here with a problem where PHP's round() function is misbehaving (i.e. round(1.4447, 2) will output 1.44 instead of 1.45) that's because round looks just 1 decimal position away from the needed precision, here's a small recursive helper function that solves the issue:
function roundFloat($float, $neededPrecision, $startAt = 7)
{
if ($neededPrecision < $startAt) {
$startAt--;
$newFloat = round($float, $startAt);
return roundFloat($newFloat, $neededPrecision, $startAt);
}
return $float;
}
Usage example:
roundFloat(1.4447, 2, 5); // Returns 1.45
Explanation:
In example above, it starts rounding from 5th decimal point (0) in this case since not stated otherwise.
You can call the function like roundFloat(1.4447, 2, 15) with same
outcome for given float 1.4447.
$startAt just defines the starting point for the "rounding process" or the required precision.
Note: all programming languages have issues with writing some floats precisely (has to do with binary, google that for more info).
Hope it helps someone.
Just encase the result in a floatval
floatval(round($myvar,2));
If you use number_format, you must add the next two parameters otherwise larger numbers will go wrong:
number_format($myvar,2, '.', '');
This tells PHP to use "." as the decimal separator and no thousands separator.
I had the same problem and my workaround (in order to not change the ini-file and possibly break something else):
$rounded = bcdiv($number, 1, 2);
Combining #PabloCamara's answer and the comment from #LorienBrune, this solution worked for me:
function roundFixed($number, $decimalPlaces)
{
return str_replace(',', '', number_format($number, $decimalPlaces));
}

Removing Zeros from decimal place if they are preceding - PHP

I am trying to format some values when I retrieve them from the database.
Some of the values look like this -
Values
121.000
0.170
12.500
12.425
0.890
Here is what I want them to look like -
Values
121
.17
12.5
12.425
.89
I have searched and searched for a solution but I can only seem to find the answer to one or the other, I need this to work dynamically in one function.
I have tried casting the values to a FloatVal but this doesn't work on 100% of the values.
Please could anyone advise?
Any more info needed please comment.
One possible way:
$val = ltrim(rtrim($num, '.0'), '0');
Demo. Actually, rtrim here is only to convert 121.0 into 121, preceding zero is, apparently, dropped with ltrim.
$value = '0.9';
echo (substr($value, 0, 2) == '0.' ? substr($value, 1) : $value);

PHP - number_format issues

number_format stupidly rounds numbers by default. Is there just a simple way to turn off the rounding? I'm working with randomly generated numbers, and I could get things like...
42533 * .003 = 127.599 or,
42533 * .03 = 1275.99 or,
42533 * .3 = 12759.9
I need number_format (or something else) to express the result in traditional U.S. format (with a comma separating the thousands) and not round the decimal.
Any ideas?
The second argument of number_format is the number of decimals in the number. The easiest way to find that out is probably to treat it as a string (as per this question). Traditional US format is default behaviour, so you don't need to specify remaining arguments.
$num_decimals = strlen(substr(strrchr($number, "."), 1));
$formatted_number = number_format($number, $num_decimals);
If anyone's interested in this, I've written a little function to get around this problem.
With credit to Joel Hinz above, I came up with...
function number_format_with_decimals($value, $round_to){
//$value is the decimal number you want to show with number_format.
//$round_to is the deicimal place value you want to round to.
$round_to_decimals = strlen(substr(strrchr($value, "."), $round_to));
$ans = number_format($value, $round_to);
return $ans;
}
I tried these solutions, but what ended up being my answer was this:
$output=money_format('%!i', $value);
This gives you something like 3,234.90 instead of 3,234 or 3,234.9

How to add numbers after decimal using php

I am having trouble thinking of a php function to add zeros after a decimal. Let say I have $money="10000" I need a function that will add .00 to 10000.00 and to add just a zero to 0 after 234.5.
can anyone help me please?
Just as Dan Grossman said; number_format is your friend here and you'd accomplish those double zeros by:
$money = "1234";
$formatedNumber = number_format($money, 2, '.', '');
echo $formatedNumber;
// 1234.00
The function is number_format
http://php.net/manual/en/function.number-format.php
Always search the PHP manual first :)
Maybe not the answer you want to hear, but I think you're better off storing these values in numeric types and formatting them properly just before output

Easy way to check that something is a number w/ max 2 decimal places of accuracy?

I want to make sure the input is A)a number and B)has at most 2 decimals.
$number[$i]=int(100*$number[$i])/100;
I imagine there is a more efficient way to do this... any suggestions? (using PHP).
number_format($number, 2, '.', '')
Regexes to the rescue:
if (preg_match('/^\d+\.\d{2}$/', $number[$i])) {
etc...
}
of course, now that regexes are involved, you've got two problems, as the old saying goes.
$number[$i] = round((float)$number[$i], 2);

Categories