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);
Related
OK lets assume I have
$value = '0.0005304';
I'm struggling to work out how I can remove all instances of 0
until another character is detected.
So in the case above the end result would be 5304
I know I should show code working out however I'm unsure on how to do this so don't know where to start looking.
Any help would be appreciated
** Added **
The 2 numbers are stock market prices , open & close
basically I want to deduct the open from the close
this value will be the difference between the 2
example open = 1.23456 close = 1.23446 is a difference of -0.00010
I would want this represented as -10 points
Hope this explains more
Try the following:
$value = '0.0005304';
$value = (int)str_replace('.','', $value);
var_dump($value); //output 5304
str_replace will remove the . and (int) will cast it to int which will remove all the 0s
Trim off the zeroes, or in your case, the zeroes and the decimal.
$value = ltrim($value, '0.');
I don't know if referring to this as "replace characters" is accurate, though. It seems we're replacing them with nothing.
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));
}
I have two float variables that are equal, I retrieve them by PHP and subtract them. the result equals (7.105427357601E-15) I tried to change to double or to decimal and none of that worked. This is what I use in PHP:
$giftcard_balance = $giftcard['balance'];
$total = $product['price'];
$total -= $giftcard_balance;
echo $total;
Here instead of showing 0, it's showing (7.105427357601E-15)
Anyone can help please?
When dealing with prices and account balances you will find that DECIMAL(6, 2) is much easier to deal with than FLOAT. If you experience the same problem when using DECIMAL datatype please post a specific example.
Using round() or similar is a very bad idea as it is simply masking the problem, not fixing it.
In order to get rid of the float inaccuracy, you can, for example, use number formatting.
$a = 7.105427357601E-15;
$b = number_format($a, 2);
echo $a , "\n", $b , "\n";
Perhaps you're looking for the php intval function.
Or maybe the round function.
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);
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