How can I check if number has one , or two decimals? - php

I would like to know how I can check if a number has one or two decimals, and if it only has one decimal , like 12,9 for example, then echo the number with an additional 0, so it looks like 12,90.
<?php
$number = '12,9';
if $number //has 2 decimals // {
echo $number; }
else {
echo $number.'0';
}
endif;
?>
I have no clue how to do that properly, any help would be really appreciated! Thanks

If your input is a . (dot) separated decimal, you can just use number_format():
number_format('12.9', 2);
Alternatively, you can use the NumberFormatter class if you need to support multiple locales or numbers with commas for decimal separators. Such as:
$formatter = new NumberFormatter('de_DE', NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $formatter->format($formatter->parse('12,9'));
Note: The use of NumberFormatter requires the intl extension. It can be added on debian based systems with a simple sudo apt-get install php5-intl.

If you're sure that the number is always formatted like you've posted, than you could do:
number_format(str_replace(',', '.', '12,9'), 2, ',', '.');

what you need is the number_format function
http://www.php.net/manual/en/function.number-format.php

Since PHP is not strictly typed, you could so something like this:
$parts = explode(",", $number);
$num_decimals = strlen($parts[1]);
if ($num_decimals == 2) //has 2 decimals // {
echo $number;
} else {
echo $number.'0';
}

Related

How to show number string value with plus or minus

I am trying to get number value with plus and minus
<?php
$num1= '-12.20000';
$num2= '+18.20000';
echo rtrim(str_replace('.00', '', number_format($num1, 2));
echo rtrim(str_replace('.00', '', number_format($num2, 2));
?>
Need output like
-12.2
+18.2
I can't see exactly what you need. There are not enough examples and your description of the task is not sufficient.
The number is formatted with a sign and 2 decimal places. If the last digit is a 0, it is removed with preg_replace().
$data = ['-12.20000','+18.20000', 234.0, 2.1234];
foreach($data as $value){
$formatVal = sprintf("%+0.2f",$value);
$formatVal = preg_replace('~(\.\d)0$~','$1',$formatVal);
echo $value.' -> '.$formatVal."<br>\n";
}
Output:
-12.20000 -> -12.2
+18.20000 -> +18.2
234 -> +234.0
2.1234 -> +2.12
If the result is only ever required with one decimal place, you can use
$formatVal = sprintf("%+0.1f",$value);
without the preg_replace.
In python, you could do it like this:
def returnWithSign(str):
n = float(str)
if n>0:
return '+{}'.format(n)
return n
Instead of using difficult functions in PHP just use the native stuff PHP brings with it. One fantastic thing of that stuff is the NumberFormatter class.
$formatter = new NumberFormatter( 'en_GB', NumberFormatter::DECIMAL );
$formatter->setTextAttribute(NumberFormatter::POSITIVE_PREFIX, '+');
$num1= '-12.20000';
$num2= '+18.20000';
echo $formatter->format($num1) . PHP_EOL;
echo $formatter->format($num2) . PHP_EOL;
Exactly does what you want.
Output: https://3v4l.org/UQX3Y

Remove trailing zeros until 2 decimals in PHP

I've tried casting to float and number_format but float will always round at two and number_format is fixed on the amount of decimals you specify.
So how can I do this like the following conversion
11.2200 -> 11.22
11.2000 -> 11.20
11.2340 -> 11.234
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
This might help, You can use sprintf given by PHP.
You can use float casting
echo (float) 11.2200;
echo "<br/>";
echo (float) 11.2000;
echo "<br/>";
echo (float) 11.2340;
and you have to check number of digits after decimal point and than get value like below :
$val=(float) 11.2000;
if(strlen(substr(strrchr($val, "."), 1))<2){
echo number_format($val,2);
}
You may use the round() function for this.
i-e round(number,precision,mode);
Example:
echo(round(11.2200,2));
Output
11.22
Thanks
Not sure if you need a fix for this anymore, but I just ran into the same problem and here's my solution:
$array = array(11.2200, 11.2000, 11.2340);
foreach($array as $x)
{
// CAST THE PRICE TO A FLOAT TO GET RID OF THE TRAILING ZEROS
$x = (float)$x
// EXPLODE THE PRICE ON THE DECIMAL (IF IT EXISTS)
$pieces = explode('.',$x);
// IF A SECOND PIECE EXISTS, THAT MEANS THE FLOAT HAS AT LEAST ONE DECIMAL PLACE
if(isset($pieces[1]))
{
// IF THE SECOND PIECE ONLY HAS ONE DIGIT, ADD A TRAILING ZERO TO FORMAT THE CURRENCY
if(strlen($pieces[1]) == 1)
{
$x .= '0';
}
}
// IF NO SECOND PIECE EXISTS, ADD A .00 TO IT TO FORMAT THE CURRENCY VALUE
else
{
$x .= '.00';
}
}

php round a float if exists and add comma if needed

I tried to check similar questions but i didn't get exact same one.So here is what i want
3.45678 to 3.46
3456789 to 3,456,789 //not 3,456,789.00
3456789.45678 to 3,456,789.46
I tried
number_format($num,2) //it adds 00 at the end
round($num,2) //no comma
If its repeated question i apologize for that and please give me the link
thank you!
function convertNumber($number) {
return str_replace('.00', '', number_format($number, $decimals=2, $dec_point='.', $thousands_sep=','));
}
The number formatter class can do that for you, plus it supports any ICU locale.
<?php
$nf = new NumberFormatter("en_US", \NumberFormatter::DECIMAL);
$nf->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
$nf->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $nf->format($number, \NumberFormatter::TYPE_DOUBLE);
Haven't tried this
<?php
if (is_float($num)) {
$num=round($num,2);
echo number_format($num, 2);
}
else {
echo number_format($num);
}
?>

PHP Currency formatting trailing zeros

Is it possible to have PHP format currency values, for example: $200 will output as: $200 (without decimals) but with a number like $200.50 it will correctly output $200.50 instead of $200.5?
Thanks! :)
$num_decimals = (intval($amt) == $amt) ? 0 :2;
print ("$".number_format($amt,$num_decimals);
If you don't mind handling the currency on your own, you can simply use the following on the number, to get the correct output.
This solution will always output trailing zeros (xx.x0 or xx.00 depending on the provided number)
$number = 1234
sprintf("%0.2f",$number);
// 1234.00
How about a custom function to handle the situation accordingly:
function my_number_format($number) {
if(strpos($number, '.')) {
return number_format($number, 2);
} else {
return $number;
}
}
you can use number_format to do this.
Example:
$Amount = 200.00;
echo "$" . number_format($Amount); //$200
There are a couple of ways. Probably the most universally supported and recommended method is sprintf.
sprintf("%01.2f", "200.5"); //200.50
sprintf("%01.2f", "10"); //10.00
number_format is good as well, and has all sorts of options, and it will add thousands separators and such if requested to do so.
There's also a money_format function, but it is unsupported on Windows servers.

PHP number: decimal point visible only if needed

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;

Categories