I have a data set returned from yahoo finance api that is formatted like the following:
167.3B
97.719B
1.322B
973.4M
77.8M
I want to only allow one digit after the decimal. I can think of a number of ways to do it but they all seem somewhat cumbersome. Anyone know a best practice?
$letter = substr($number, -1);
$output = round($number, 1) . $letter;
This will round to the nearest 10th of an integer
You could do:
round(floor($number)*10)/10
If $number equaled 5.69 that would return 5.6, but rounding will be more accurate and is considered the best practice.
Another option:
number_format($number, 1)
Related
I am currently echoing a number like this:
<?php echo $enterprise_platinum_price ?>
The problem is that the number normally has a decimal place such as 19.44 or 13.353
I need to display the full number but without the decimal point or any of the numbers behind it. I know that you can round to the full number in PHP but I don't ever want it to round up. If the only way to do this is with rounding, I need it to always round down...
Use the math floor function to round downward.
$a = floor(1.99); // $a = 1
You can also do it without rounding using number_format. There's many, many more ways, but I think the floor() option is the shortest for you.
$a = number_format(1505.99, 0, '', ''); // $a = 1505
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
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've been wrestling with PHP's ceil() function giving me slightly wrong results - consider the following:
$num = 2.7*3; //float(8.1)
$num*=10; //float(81)
$num = ceil($num); //82, but shouldn't this be 81??
$num/=10; //float(8.2)
I have a number which may have any number of decimal places, and I need it rounded up to one decimal place.
i.e 8.1 should be 8.1, 8.154 should be 8.2, and 8 should be left as 8.
How I've been getting there is to take the number, multiply by 10, ceil() it, then divide by ten but as you can see I'm getting an extra .1 added in some circumstances.
Can anyone tell my why this is happening, and how to fix it?
Any help greatly appreciated
EDIT: had +=10 instead of *=10 :S
EDIT 2:
I didn't explicitly mention this but I need the decimal to ALWAYS round UP, never down - this answer is closest so far:
rtrim(rtrim(sprintf('%.1f', $num), '0'), '.');
However rounds 3.84 down to 3.8 when I need 3.9.
Sorry this wasn't clearer :(
Final Edit:
What I ended up doing was this:
$num = 2.7*3; //float(8.1)
$num*=10; //float(81)
$num = ceil(round($num, 2)); //81 :)
$num/=10; //float(8.1)
Which works :)
This is more than likely due to floating point error.
http://support.microsoft.com/kb/42980
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
http://joshblog.net/2007/01/30/flash-floating-point-number-errors/
http://en.wikipedia.org/wiki/Floating_point
You may have luck trying this procedure instead.
<?php
$num = 2.7*3;
echo rtrim(rtrim(sprintf('%.1f', $num), '0'), '.');
Floats can be a fickle thing. Not all real numbers can be properly represented in a finite number of binary bits.
As it turns out, a decimal section of 0.7 is one of those numbers (comes out 0.10 with an infinity repeating "1100" after it). You end up with a number that's ever so slightly above 0.7, so when you multiply by 10, you have a one's digit slightly above 7.
What you can do is make a sanity check. Take you float digit and subtract it's integer form. If the resulting value is less than, say, 0.0001, consider it to be an internal rounding error and leave it as-is. If the result is greater than 0.0001, apply ceil() normally.
Edit: A fun example you can do if you're on windows to show this is to open up the built in calculator application. Put in "4" then apply a square root function (with x^y where y=0.5). You'll see it properly displays "2". Now, subtract 2 from it and you'll see that you don't have 0 as a result. This is caused by internal rounding errors when it attempted to compute the square root of 4. When displaying the number 2 earlier, it knew that those very distant trailing digits were probably a rounding error, but when those are all that's left, it gets a bit confused.
(Before anybody gets onto me about this, I understand that this is oversimplified, but nonetheless I consider it a decent example.)
Convert your number to a string and ceil the string.
function roundUp($number, $decimalPlaces){
$multi = pow(10, $decimalPlaces);
$nrAsStr = ($number * $multi) . "";
return ceil($nrAsStr) / $multi;
}
The problem is that floating point numbers are RARELY what you expect them to be. Your 2.7*3 is probably coming out to be something like 81.0000000000000000001, which ceil()'s up to 82. For this sort of thing, you'll have to wrap your ceil/round/floor calls with some precision checks, to handle those extra microscopic differences.
Use %f instead of %.1f.
echo rtrim(rtrim(sprintf('%f', $num), '0'), '.');
Why not try this:
$num = 2.7*3;
$num *= 100;
$num = floor($num);
$num /= 10;
$num = ceil($num);
$num /= 10;
When 10000-100, then result should be 9900.
I tried when I use:-
< ?php
$num1 = number_format(round(10000,1),2);
$num2 = number_format(round(100,1),2);
echo $num1 - $num2;
?>
The above result is -90, that made me realize that the number_format function is not applicable in calculations.
Would there be any way that I can convert a value of number_format (obtained from POST from a previous page) back to numerical value for normal calculation?
To start, the reason is that:
(int) "10,000.00"
resolves to 10 since it stops parsing at the first non-numeric character. Thanks to PHP's weird type system, this is done implicitly when you subtract the strings.
Yes, you can strip out the commas easily:
$unformatted = str_replace(",", "", $formatted);
but it's cleaner to just post the raw numeric value (you can still use number_format for the displayed value).
EDIT: It is good practice to explicitly convert numeric strings (without commas) to float (or int) with either a cast ((int) or (float)) or the function version (intval or floatval).
I don't think you can perform this 10,000.00 -100.00 with the comma in the equation. Just perform the raw arithmetic operation then format the answer.
$num1 = 10000;
$num2 = 100;
echo number_format(round($num1 - $num2,1),2);
This outputs
9,900.00
There is an easier way.
number_format is for fomating output numbers or to round easy numbers.
number_format gives us power to make well fomed rounded numbers, for a better user experience.
For calcualtion and saving Numbers in your MYSQL Database use this.
Save your Numbers in MYSQL always as type DECIMAL not FLOAT. There are lots of bugs if you want to calculate with FLOAT fields.
Than use the english notation.
$number = 1234.56;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', ''); //
// 1234.57
And now you can calculate and save it, without any Bugs.
Always Remember yourself, Saving numbers into $var is always a string.
Yeah, you can deifine type, but it doesn't matter in first case, and its to long to explain here.
For more information about number_format see here -> http://php.net/manual/en/function.number-format.php