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

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))))))

Related

Always round up on first decimal

I want my variable's first decimal to always be rounded up. For example:
9.66 goes to 9.7
9.55 goes to 9.6
9.51 goes to 9.6
9.00000001 goes to 9.1
How do I do this?
Use round() with an optional precision and round type arguments, e.g.:
round($value, 1, PHP_ROUND_HALF_UP)
The optional second argument to round() is the precision argument and it specifies the number of decimal digits to round to. The third optional argument specifies the rounding mode. See the PHP manual for round for details.
Using round() does not always round up, even when using PHP_ROUND_HALF_UP (e.g. 9.00001 is not rounded to 9.1). You could instead try to use multiplication, ceil() and division:
ceil($value * 10.0) / 10.0
Since these are floating-point values, you might not get exact results.
I made couple tests and suggest the following answer with test cases
<?php
echo '9.66 (expected 9.7) => '.myRound(9.66).PHP_EOL;
echo '9.55 (expected 9.6) => '.myRound(9.55).PHP_EOL;
echo '9.51 (expected 9.6) => '.myRound(9.51).PHP_EOL;
echo '9.00000001 (expected 9.1) => '.myRound(9.00000001).PHP_EOL;
echo '9.9 (expected ??) => '.myRound(9.9).PHP_EOL;
echo '9.91 (expected ??) => '.myRound(9.91).PHP_EOL;
function myRound($value)
{
return ceil($value*10)/10;
}
I'm not a php programmer so will have to answer in "steps". The problem you have is the edge case where you have a number with exactly one decimal. (e.g. 9.5)
Here's how you could do it:
Multiply your number by 10.
If that's an integer, then return the original number (that's the edge case), else continue as follows:
Add 0.5
Round that in the normal way to an integer (i.e. "a.5" rounds up).
Divide the result by 10.
For step (2), sniffing around the php documentation reveals a function bool is_int ( mixed $var ) to test for an integer.
You will need a custom ceil() function, your requirements cannot be satisfied by the default function or by the round.
Use this: online test
You can use this technique. Just explode the given number / string, get the number which is next value / digit of the .. after getting this you need to increment that value and check if the value is greater than 9 or nor, if then divide that and add the carry to the first portion of the main number.
$var = '9.96';
$ar = explode(".", $var);
$nxt = substr($ar[1], 0, 1) + 1;
if($nxt > 9){
$tmp = (string) $nxt;
$num = floatval(($ar[0] + $tmp[0]).".".$tmp[1]);
}
else
$num = floatval($ar[0].".".$nxt);
var_dump($num); // float(10)

Format a decimal number in PHP

I'm trying to format specific numbers up to 8 decimals by deleting unnecessary zeros.
My actual code is:
rtrim(sprintf("%.8f", $upto_eight_decimals), '0')
It actually prevents to format a number as 0.00012 into 1.2E-4 or 0.00012000
However, with numbers integer such as 1 it gets converted into 1. but this point is not my expected result (I know because of rtrim deleting all zeros).
UPDATE: rtrim(rtrim(sprintf("%.8f", $upto_eight_decimals), '0'), '.') it looks like working
You can do it this way, Just use number_format:
$upto_eight_decimals = "0.0001200";
$out = number_format((float)$upto_eight_decimals, 8, '.', '');
echo preg_replace("/\.?0*$/",'',$out);
or
echo $out + 0;
This function returns a string.
This will work for you, let me know is it work or not.

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 simplexml -- formatting integers

I'm using simplexml to recover xml from a remote server, and I get values that can look something like this:
1.28586732
-1.2357956
I save these values in a variable but I would like to:
Display each value with no more than 2 decimal places
Have a plus sign precede the value if it is positive
Apply different CSS styles depending on whether the value is positive or negative (for instance display value in red if it is negative)
Thanks!
To display only 2 decimal places you can either use round($num, 2) or sprintf("%.2f", $num), the difference is that sprintf always returns 2 decimal places, i.e. 5 would be 5.00, while round only shows the necessary amount of decimal places. sprintf is also locale-aware.
To have a plus sign precede the value, you would simply do if ($num >= 0) $num = '+'.$num;
And finally to do CSS styling, you should wrap the number in a span and give it a class, i.e. either positive or negative.
To do all of the three, you could have a function like this:
function format_decimal($num)
{
return sprintf(
'<span class="%s">%+.2f</span>',
$num < 0 ? 'negative' : 'positive',
$num
);
}
let:
$s=1.2344545665
if($s>=0)
{
echo "<div class=\"addclass\">+".roundDigits($s,2) . "</div>";
}
else
{
echo "<div class=\"minusclass\">-".roundDigits($s,2) . "</div>";
}
Check out number_format. http://php.net/manual/en/function.number-format.php Then if >= 0 for a positive, <= negative checks.

Conditional formatting of a float in 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);

Categories