PHP number: decimal point visible only if needed - php

I'd like to know if exists some function to automatically format a number by it's decimal, so if I have:
<?php
// $sql_result["col_number"] == 1,455.75
number_format ($sql_result["col_number"], 2, ".", "");
// will return 1455.75
// $sql_result["col_number"] == 1,455.00
number_format ($sql_result["col_number"], 2, ".", "");
// could I get 1455 instead of 1455.00?
?>
so my answer is if does exist some way to remove the decimals if I have DECIMAL data forma in my DB only when it's round?
Or shoud I do something like that?
<?php
// $sql_result["col_number"] == 1,455.00
str_replace(".00", "", (string)number_format ($sql_result["col_number"], 2, ".", ""));
// will return 1455
?>

floatval or simply casting to float
php > echo floatval(7.00);
7
php > echo floatval(2.30);
2.3
php > echo floatval(1.25);
1.25
php > echo floatval(1.125);
1.125
php > echo (float) 7.00;
7
php > echo (float) 2.30;
2.3
php > echo (float) 1.25;
1.25
php > echo (float) 1.125;
1.125

I actually think that your workaround is as good as any. It's simple and clear, and there's really no point talking about performance here, so just go for it.

As Emil says yours are good. But if you want to remove 0 from e.g. 7.50 too, I've got a suggestion, rtrim():
<?php
// if $sql_result["col_number"] == 1,455.50
rtrim(rtrim(number_format($sql_result["col_number"], 2, ".", ""), '0'), '.');
// will return 1455.5
?>

You could also use rtrim(), which would remove excess 0s, in the case where you might want to keep one decimal place but not the excess zeros. (For example, 4.50 becomes 4.5.) Also allows you to change the number of decimal places from 2 to any other number.
rtrim(rtrim((string)number_format($value, 2, ".", ""),"0"),".");
// 4.00 -> 4
// 4.50 -> 4.5
// 4.54000000 -> 4.54 (if you're doing more decimal places)

Actually I think the cleanest way I can think of to do this for someone that just did a search looking for this sort of thing is to do this:
( number_format ($sql_result["col_number"], 2) * 100 ) / 100;

I've been accused of doing something like this:
floatval($foo) == intval($foo) ? number_format($foo) : number_format($foo,2);

If you are targeting US currency I like to use this method:
function moneyform($number, $symbol = true) {
return str_replace(".00", "", money_format(($symbol? '%.2n' : "%!n"), $number));
}
moneyform(1300999);
-->$1,300,999
moneyform(2500.99);
-->$2,500.99
moneyform(2500.99, false);
-->2,500.99

Mine since most quantity or pieces do not require decimal, this function will only show decimal when needed.
str_replace(".00", "", number_format($this->pieces, 2));

Warren.S answer helped me out. I didn't need the number_format function, so I just did this
$value=$value-0;
But in the OP's case, he needs number_format to remove the commas. So this would work for him
$value=number_format ($sql_result["col_number"], 2, ".", "")-0;

Since I could not find a flexible solution I wrote a simple function to get the best result:
function getValueFormattedWithMinimalDecimals($value, $max_decimals = 2, $dec_point = ',', $thousands_sep = '') {
$bestNumberOfDecimals = -1;
$decimal = 0;
while ($decimal <= $max_decimals) {
$bestNumberOfDecimals = $decimal;
$valueDecimals = number_format($value, $decimal);
if (floatval($value) == $valueDecimals) {
break;
}
$decimal++;
}
if($bestNumberOfDecimals > 0 && number_format($value, $bestNumberOfDecimals) == number_format($value, 0)) {
$bestNumberOfDecimals = 0;
}
return number_format($value, $bestNumberOfDecimals, $dec_point, $thousands_sep);
}

What about
number_format($value,2) - 0;

Related

number_format() php remove trailing zeros

Is there a way with number_format() to leave out decimal places if the number is not a float/decimal?
For example, I would like the following input/output combos:
50.8 => 50.8
50.23 => 50.23
50.0 => 50
50.00 => 50
50 => 50
Is there a way to do this with just a standard number_format()?
You can add 0 to the formatted string. It will remove trailing zeros.
echo number_format(3.0, 1, ".", "") + 0; // 3
A Better Solution: The above solution fails to work for specific locales. So in that case, you can just type cast the number to float data type. Note: You might loose precision after type casting to float, bigger the number, more the chances of truncating the number.
echo (float) 3.0; // 3
Ultimate Solution: The only safe way is to use regex:
echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3
Snippet 1 DEMO
Snippet 2 DEMO
Snippet 3 DEMO
If you want to use whitespace here is better solution
function real_num ($num, $float)
{
if (!is_numeric($num) OR is_nan($num) ) return 0;
$r = number_format($num, $float, '.', ' ');
if (false !== strpos($r, '.'))
$r = rtrim(rtrim($r, '0'), '.');
return $r;
}
Use:
$a = 50.00;
$a = round($a, 2);
Even though the number has 2 zeros trailing it, if you round it, it won't show the decimal places, unless they have some kind of value.
So 50.00 rounded using 2 places will be 50, BUT 50.23 will be 50.23.
Unless you specify at which point to round up or down, it won't change your decimal values. So just use default round()

PHP number_format is rounding?

I have a price "0,10" or "00000,10"
Now when i try
number_format($price, 2, ',', '')
I get 0,00.
How can i fix this? I want 0,10 $.
I don't want rounding.
Or when i have 5,678, i get 5,68. But i want 5,67.
Several people have mentioned rounding it to 3 and then dropping the last character. This actually does not work. Say you have 2.9999 and round it to 3 it's 3.000.
This is still not accurate, the best solution is this:
$price = '5.678';
$dec = 2;
$price = number_format(floor($price*pow(10,$dec))/pow(10,$dec),$dec);
What this does is takes the price and multiplies it by 100 (10^decimal) which gives 567.8, then we use floor to get it to 567, and then we divide it back by 100 to get 5.67
You can increase the size of the number before rounding down with floor:
$price = floor($price * 100) / 100;
$formatted = number_format($price, 2, ',', '');
Another solution, which may give better precision since it avoids floating-point arithmetic, is to format it with three decimals and throw away the last digit after formatting:
$formatted = substr(number_format($price, 3, ',', ''), 0, -1);
you should convert comma-filled number back to normal decimal before with str_replace.
$number = str_replace(",", ".", $number);
and then you can use number_format
"00000,10" is a string. You should a decimal point. To get the desired behaviour, you could use:
echo substr(number_format(str_replace(',', '.', $price), 3, ',', ''), 0, -1);
Use this (needs activated intl PHP extension)
$numberFmtCurrency = new NumberFormatter('de_AT', NumberFormatter::CURRENCY);
$numberFmtCurrency->setAttribute(NumberFormatter::ROUNDING_INCREMENT, 0);
$numberFmtCurrency->formatCurrency(328.13, 'EUR'); // prints € 328.13 (and not 328.15)
If you are literally just wanting to clear leading zeroes and just limit the length, rather than round to a certain amount of decimal places, a more generalised solution could be this function:
function cutafter($string,$cutpoint,$length)
{
$temp = explode($cutpoint,$string);
$int = $temp[0];
$sub = $temp[1];
return number_format($int,0).','.substr($sub,0,$length);
}
Example:
$number = "005,678";
$answer = cutafter($number,",",2);
$answer now equals "5,67"
Just before number_format is executed the string "0,10" is converted by php to an number. because php always uses the engish notation the it won't look after the comma.
echo "4 apples" + 2;
output: 6
The " apples" part is ignored just as your ",10" is ignored.
Converting the "," to a "." allows php to see the other digits.
$price = str_replace(',', '.', '0,10');
number_format($price, 2, ',', '');
My problem was that html validator error messege thar number_format() argument is not double.
I solved this error message by placing floatval for that argument like number_format(floatval($var),2,'.',' ') and that is working good.
function format_numeric($value) {
if (is_numeric($value)) { // is number
if (strstr($value, ".")) { // is decimal
$tmp = explode(".", $value);
$int = empty($tmp[0]) ? '0' : $tmp[0];
$dec = $tmp[1];
$value = number_format($int, 0) . "." . $dec;
return $value;
}
$value = number_format($value);
return $value;
}
return $value; // is string
}
Unit Testing:
Passed / 1100000 => 1,100,000
Passed / ".9987" => .9987
Passed / 1100.22 => 1,100.22
Passed / 0.9987 => 0.9987
Passed / .9987 => 0.9987
Passed / 11 => 11
Passed / 11.1 => 11.1
Passed / 11.1111 => 11.1111
Passed / "abc" => "abc"
See this answer for more details.
function numberFormat($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',')
{
$negation = ($number < 0) ? (-1) : 1;
$coefficient = pow(10, $decimals);
$number = $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
return number_format($number, $decimals, $decPoint, $thousandsSep);
}

In PHP, how to print a number with 2 decimals, but only if there are decimals already?

I have a basic index.php page with some variables that I want to print in several places - here are the variables:
<?php
$firstprice = 1.50;
$secondprice = 3.50;
$thirdprice = 20;
?>
My challenge is that later in the document, when I print, I get the prices without the second '0' in the price - this is what happens:
<?php print "$firstprice";?> // returns 1.5 - not 1.50!
SO - I know how to do this with JS, but how is this done in PHP 5+? Basically I want to print the second '0' if there is already a decimal, so if the variable is equal to '3', it stays as '3', but if it's equal to '3.5' it converts to display '3.50' with a second '0', etc.
Here's a JS example - what's the PHP equivalent?
JS:
.toFixed(2).replace(/[.,]00$/, ""))
Many thanks!!
This is simple and it will also let you tweak the format to taste:
$var = sprintf($var == intval($var) ? "%d" : "%.2f", $var);
It will format the variable as an integer (%d) if it has no decimals, and with exactly two decimal digits (%.2f) if it has a decimal part.
See it in action.
Update: As Archimedix points out, this will result in displaying 3.00 if the input value is in the range (2.995, 3.005). Here's an improved check that fixes this:
$var = sprintf(round($var, 2) == intval($var) ? "%d" : "%.2f", $var);
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
more info here
http://php.net/manual/en/function.number-format.php
You could use
if (is_float($var))
{
echo number_format($var,2,'.','');
}
else
{
echo $var;
}
What about something like this :
$value = 15.2; // The value you want to print
$has_decimal = $value != intval($value);
if ($has_decimal) {
echo number_format($value, 2);
}
else {
echo $value;
}
Notes :
You can use number_format() to format value to two decimals
And if the value is an integer, just display it.
you can use number_format():
echo number_format($firstprice, 2, ',', '.');
Alternatively way to print
$number = sprintf('%0.2f', $numbers);
// 520.89898989 -> 520.89

How do I echo a variable thats a double, but only show the decimal places if they're needed?

I have some double fields in my database and when echoing the fields out in my php I get .00 at the end of the values.
How do I get the .00 not to display, but display if there is a value?
You can use str_replace to remove the ".00" from the values.
$value = 10.00;
echo str_replace('.00', '', $value); // 10
$value = 10.52;
echo str_replace('.00', '', $value); // 10.52
echo (int)$double;
will simply strip off the decimal places. if you merely want to hide 'zero' decimals (10.00 -> 10), but leave non-zero decimals (10.1 -> 10.1), then you'd need to do some processing:
echo preg_replace('/\.0+$/', '', $double);
which would handle any number of zeroes after the decimal place, but leave non-zeroes in place.
if (fmod($number, 1) == 0)
{
$number = intval($number);
}
else
{
$number = round($number, 2);
}
Or just use round() [# ideone.com]:
var_dump(round($number = 5.00, 2)); // 5
var_dump(round($number = 5.01, 2)); // 5.01
For an arbitrary number of 0s at the end of the number:
$number = rtrim($number,".0");
Examples:
Input : 1.00
Result: 1
Input : 1.25
Result: 1.25
Input : 1.40
Result: 1.4
Input : 1.234910120000
Result: 1.23491012
select number,if(number % 1 = 0,cast(number as unsigned),number)
from table

Percentage display issue

i have a value that i calculate between 0 -100 ,
its usually a float number like 5.87876 , so i use number_format like :
$format_number = number_format($number, 2, '.', '');
the problem is , even the calculate number is integer like : 100
its show 100.00
but i want to display it like : 100
what is the elegant way to achive this ?
(i mean without else if ..)
This is the shortest way I know.
$digits = (is_numeric($number) && intval($number) == $number ? 0 : 2);
$format_number = number_format($number, $digits, '.', '');
The is_numeric and intval trick is taken from this SO question
so you are trying to have an accuracy of two decimal places after the dot, but suppress the .00 on integers? I'd use sprintf:
$numbers = Array(3.141, 5.87876, 10.9999, 100);
foreach( $numbers as $n ) {
$string = sprintf("%6.2f\n", $n);
$string = str_replace(".00", " ", $string);
echo $string;
}
The output is
3.14
5.88
11
100

Categories