Conditional formatting of a float in PHP - php

I'm retrieving a float value from a mysql database on a php page (2.5, 3.0 etc)
I would like to format this value so that if it is actually an integer, it should show zero decimal places. (it should output 3 instead of 3.0, but output 2.5 as 2.5)
What would be the simplest way to achieve this?

I would try something along the lines of:
echo (intval($v) == $v) ? intval($v) : $v;
But I wonder if there's a more efficient way.

You could also do the formatting in your query, it is likely to be faster than doing it in php especially if you have many rows to process.
Something like:
SELECT
CASE
WHEN t.myColumn % 1 = 0
THEN FORMAT( t.myColumn, 0 )
ELSE FORMAT( t.myColumn, 2 )
END AS `formatted`
...
FROM myTable t
WHERE ...
The same method does apply for php if you want to do it outside the database:
$displayValue = $myValue % 1 == 0
? number_format( $myValue, 0 )
: number_format( $myValue, 2 );

You could also use a printf if you want to control the number of digits displayed to the right of the decimal point:
if (intval($v) == $v) printf("%d", intval($v)); else printf("%0.2f", $v);

Related

How to add numeric value to value without adding or subtracting it in php

I would like to post a value to my MySQL database in this format;
01, 02, 03...
011, 012, 013...
0101, 0102, 0103,
etc.
(with a 0 before each value).
If I do it like this "01+1" I (understandable) get the value 2 and not "02".
is there a default php function that let's me set the default amount of characters or is there an other option?
I'm using laravel combined with eloquent and some own functions like so;
$lastSKU = $data->GetData('get', 'products', 'filter')->max('SKU');
$newValue = $lastSKU+1;
Thanks in advance.
It sounds like you won't know how the format will be, if there is always a 0 in front it is easy enough to do
$value = '0'. ( $value + 1 );
PHP will automatically convert it to a number between the brackets and by adding a string to it it will become a string again.
Now if you do not know the the length or the padding in advance but you do need to keep the current padding I would suggest something like
$value = str_pad(($value + 1), strlen($value), '0', STR_PAD_LEFT);
Edit, str_pad is a bit slow these days, sprintf can do the same trick but much faster
$value = sprintf("%'.0" . strlen($value) . "d\n", ($value +1));

Format number as currency

I am (learning) using PHP to select column data from MySQL into an array using this, CONCAT('$',FORMAT(price, '5')) as price and it outputs $1,751.60000 or $10.00230 or $7.23000 which is great.
However, I would like to remove the trailing zeros but still be able to have a minimum of two decimal places
$1,751.60000 = $1,751.60
$10.00230 = $10.0023
$7.23000 = $7.23
I have read a number of similar post regarding number to currency conversion but none doesn't seem to solve my problem as they remove all the trailing zeros.
We will implement this in two way.(Mysql, PHP).
MYSQL:
FORMAT('price', 2 ) This is mysql function. It takes first parameter as value & second parameter is the number of decimal places.
Syntax:
FORMAT( value, Decimal );
Example:
FORMAT('1751.60000', 2 ) => 1751.60 // Output
FORMAT('1751.60000', 3 ) => 1751.600 // Output
PHP:
In PHP we have number_format() function. This is working same as MYSQL.
Syntax:
number_format( value, Decimal );
Example:
number_format('1751.60000', 2 ) => 1751.60 // Output
number_format('1751.60000', 3 ) => 1751.600 // Output
The Best way is to implement at MYSQL.
Note: These both function round up the values.
I will post this code in PHP since it is easier for me.
$price = $row['price']; // the original price
if (number_format($price, 2) == $price) {
echo '$'.number_format($price, 2);
} else {
echo '$'.rtrim(number_format($price, 5),'0');
}
rtrim will remove any trailing character specified. In this case, remove trailing zeros.
Note : I only put this code number_format($price, 5) because of the sample of the question. If you wish to keep all decimal number minus trailing zeros, just using $price is enough.

Echo decimal value without point zero ( .0 ) at end

I am using
Decimal (5,1)
to store my data.
When value is 12.2, 66.4... evething is ok.
But the NOT decimal value : 5, 10 , 20 .... when echo will be 5.0, 10.0 ...
How can I echo them look like :
1, 2.2, 2.5, 10, 10.5, 10.6, 11
Gordon Linoff's answer may do the trick, but here is the PHP way to do so :
echo (intval($var) == $var) ? intval($var) : $var;
Or, if you don't like ternary conditions :
if (intval($var) == $var) {
echo intval($var);
} else {
echo $var;
}
You need to look at the value and decide how to format it. The type specification says "keep one digit after the decimal place", and MySQL diligently does that.
There are lots of ways. Here is one:
select (case when val = cast(val as int) then format(val, 0)
else format(val, 10) end)
Format adds commas, which (to me) seems desirable for numbers greater than 1,000. But there are other methods if you don't like that.
A generic solution working for any number of fractional digits:
remove all trailing zeroes and if the last character is a period, remove it too:
TRIM(TRAILING '.' FROM (TRIM(TRAILING '0' FROM (CAST(col AS VARCHAR(40))))))

sprintf (or other function) for contitional formatting of integer / float

I need to display a number registered in database as a float
If the number ha no decimal part, is should be displayed as an int, and as a decimal in other cases.
Example :
8.00 should be displayed 8
8.45 should be displayed 8.45
The existing code uses a weird (but functionnal solution) using roud() :
if(round($number) == $number) {
$number = round($number);
}
I wish to find some solution with sprintf by example, to have a more self-explicating code (the actual solution with round is not very understandable)
Does any of you faced this problem and knows a solution
(I've tried to play with sprintf() but I dit not managed how to have a variable number of decimals)
Try this:
$numbers = array(
8.00, 8.45, 20.00, '8.00', '8.45', '20.00'
);
foreach ($numbers as $nr) {
echo (string)(double)$nr, '<br />';
}
echo +'8.45';
will display 8.45 and
echo +'8.00';
will display 8 ;)
Not quite sure this is what you're looking for, but to shorten your rounding code into one statement, use this.
$number = (int)$number == $number ? (int)$number : $number;

PHP OCI, Oracle, and default number format

When I execute a fetch from an Oracle database using PHP OCI, numbers that are less than 1 are shown as .XXXXXX, e.g. .249999. Is there a way to set this to 0.XXXXXX or to any other format, without modifying every query to use to_char() explicitly? (Perhaps through some session parameters?)
Using PHP you can easily add the 0, by converting to float:
$a = '.249999';
echo (float) $a;
Meaning you can convert your number by
$row['number'] = (float) $row['number'];
after fetching it from the DB.
There is no way to do what you're asking globally short of modifying php/oci-extension source code. The reason for this behavior is because oracle oci omits 0s in results and php converts all results from oci to strings without performing any casting depending on column datatype. Even results in SQL*Plus omit 0 by default, and SQL*Plus formatting has to be invoked with set numformat to customize column formatting and prepend 0s.
There is currently no alter session parameter you can set to change this behavior.
Most common way to work around this is to use a wrapper around your queries and check for numeric columns with is_numeric and then format the numeric column values with number_format or sprintf. Hopefully your application already uses a wrapper around stock php oci functions so you can make the change in one location.
If you need to fix decimals numbers in multiple rows, here's a function to solve it.
function fixDecimalNumbers(array $fetchedDataset)
{
//workaround for Oracle driver not returning leading zero on decimal numbers between -1 and 1 -.-
foreach($fetchedDataset as $rownum => $row){
foreach($row as $column => $value) {
if(substr( $value, 0, 2 ) === '-,' && is_numeric(substr( $value, 2, 1 ))){
$row[$column] = '-0' . substr( $value, 1);
error_log($column);
error_log($value);
}
else if(substr( $value, 0, 1 ) === ',' && is_numeric(substr( $value, 1, 1 ))){
$row[$column] = '0' . $value;
}
}
$fetchedDataset[$rownum] = $row;
}
return $fetchedDataset;
}
The simplest option
$a = '.249999';
echo ($a*1);

Categories