number_format without decimal argument - php

I would like to use the number_format() function without to specify the number of decimals. (If 2 decimals, display 2, if 5, display 5)
Is that possible?
Thanks a lot

You can calculate the number of decimals before you use numberformat and use that in the function.
$number = 50001/4;
If(strpos($number, ".") !== false){
// Is float
$decimals = strlen($number) - (strpos($number, ".")+1);
}Else{
// Is integer == no decimals
$decimals =0;
}
Echo number_format($number, $decimals, ',', ' ');
https://3v4l.org/DULp4

If this is really what you want, this may work even if this is totally useless
function numberOfDecimals($value)
{
if ((int)$value == $value)
{
return 0;
}
else if (! is_numeric($value))
{
// throw new Exception('numberOfDecimals: ' . $value . ' is not a number!');
return false;
}
return strlen($value) - strrpos($value, '.') - 1;
}
$number = 1.23456;
print number_format($number,numberOfDecimals($number));
credits : PHP: get number of decimal digits

Related

PHP Round decimals always up to the nearest highest decimal

I would like to create a rounding methode to round decimals always up to the closest highest decimal value.
for example: 51.13 => 51.20 or 22.33 => 23.40 but lets say 30.10 stays 30.10
Is this even possible?
Sorry if my explonation is bad but my math english is not the best.
maybe custom function for rounding ?
something like this
$inputNumber=51.13;
function round2deci($number){
$explode = explode(".", $number);
/// 51.13 == 51.ab
$a = substr($explode[1], 0, 1);
$b = substr($explode[1], 1, 2);
// fix for 51.91
if($a == 9){
$explode[0]++;
$a = 0;
$b = 0;
}
if($b > 0){
$a++;
}
echo $explode[0].".".$a."0";
}
round2deci($inputNumber);
and result is :
51.20
I found this answer on the php.net website under the ceil docs that does exactly what you want.
I've added an improved version below which returns a pure float where you'd be able to apply number_format to preserve the trailing zeros of the decimals:
function ceil_dec(float $number, int $precision = 2, string $separator = '.') : float
{
$numberpart = explode($separator, (string)$number);
$numberpart[1] = substr_replace($numberpart[1], $separator, $precision, 0);
if ($numberpart[0] >= 0) {
$numberpart[1] = ceil($numberpart[1]);
} else {
$numberpart[1] = floor($numberpart[1]);
}
$ceil_number = [$numberpart[0], $numberpart[1]];
return (float)implode($separator, $ceil_number);
}
var_dump(
ceil_dec(10.23,1)
);
The above code is good for PHP 7.0 and above, and with declare(strict_types = 1) enabled.

PHP slightly increment value based on number of decimals

I am trying to slightly increment a value based on the number of decimals it has.
For example if the value is 1.2 I would increase it by 0.1, 12.345 by 0.001, 12.345678 by 0.000001, etc.
I currently have a long implementation using a chain of if, else if. I know this is not the most efficient way and a loop can be used, but I was unsure of how to structure the loop. I tried using the PHP substr_replace function, but I could not get it to work for this.
Is there another way I can structure a loop to reduce my lines of code and be more efficient?
Here is my php code so far:
$valueOne = 12.345678;
// get amount of decimals
$decimal = strlen(strrchr($valueOne, '.')) -1;
/*
this also works for finding how many decimals
$test = floatval($valueOne);
for ( $decimal_count = 0; $test != round($test, $decimal_count); $decimal_count++ );
echo $decimal_count;
*/
// see value before change
echo $valueOne;
if ($decimal == "1") {
$valueOne = $valueOne + 0.1;
}
else if ($decimal == "2") {
$valueOne = $valueOne + 0.01;
}
else if ($decimal == "3") {
$valueOne = $valueOne + 0.001;
}
// etc ...
// see value after change
echo $valueOne;
/*
i tried messing around with using a loop, but did not have much luck
$start = 0.1;
$count = 0;
$position = 2;
while ($count != $decimal) {
echo substr_replace($start, 0, $position, 0) . "<br />\n";
$count++;
//$position++;
}
*/
Get the number of digits after the decimal. Then create a number with a decimal point, one less 0, followed by 1, to get the amount to add.
$valueOne = 12.345678;
// get amount of decimals
$decimal = strlen(strrchr($valueOne, '.')) -1;
// see value before change
echo $valueOne . "<br>\n";
// Get amount to add
$increment = '.' . str_repeat('0', $decimal-1) . '1';
$valueOne += $increment;
echo $valueOne;
Get the number of decimals
Multiply by the appropriate factor so the number is now an integer
Increment by 1
Divide by the same factor to get back to the original number (properly incremented)
function increment($number){
// get amount of decimals
$decimal = strlen(strrchr($valueOne, '.')) -1;
$factor = pow(10,$decimal);
$incremented = (($factor * $number) + 1) / $factor;
return $incremented;
}

Hexadecimal String Incrementation

It might be an easy two lines code but I've spend the last two hours searching and trying every solution out there in vain.
Using PHP 5.6, I want to increment the value of a string that I get from my Database.The string contains an hexadecimal number for example ffffffff000000000001586f I want to increment it to get ffffffff0000000000015870
I have tried to convert my string with hexdec and dechex , String2hex ... but I always get a wrong result
Using functions from http://php.net/manual/en/ref.bc.php#99130
<?php
function bchexdec($hex) {
if(strlen($hex) == 1) {
return hexdec($hex);
} else {
$remain = substr($hex, 0, -1);
$last = substr($hex, -1);
return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
}
}
function bcdechex($dec) {
$last = bcmod($dec, 16);
$remain = bcdiv(bcsub($dec, $last), 16);
if($remain == 0) {
return dechex($last);
} else {
return bcdechex($remain).dechex($last);
}
}
echo bcdechex(bcadd(bchexdec('ffffffff000000000001586f'), 1));
https://3v4l.org/fXneg

PHP Allow only numbers with 2 decimals

I need a function to check if number have 2 decimals or not.
For example:
$number = '1.00'; // Valid
$number2 = '1'; // Not valid
$number3 = '1.000' //Not valid
You can check it like that:
$str = "1.23444";
print strlen(substr(strrchr($str, "."), 1));
You would have to convert your variable to a String, but this is not a big problem. Do it like that:
$d = 100.0/81.0;
$s = strval($d);
You can do something like this:
if(strlen(substr(strrchr($number, "."), 1)) == 2){
echo "valid";
}else{
echo "not valid";
}
Regex could be a solution since your numbers seem to be declared as strings.
Code :
<?php
$re = "/(\d\.\d{2})(?!\d)/";
$array_input = array('1.00', '1', '1.000');
foreach($array_input as $row)
{
if(preg_match($re, $row, $matches) == 0)
echo $row . " isn't a valid value with 2 decimals only. <br>";
else
echo $row . " is valid. <br>";
}
?>
Output :
1.00 is valid.
1 isn't a valid value with 2 decimals only.
1.000 isn't a valid value with 2 decimals only.
Why would you not just force them to have 2 decimals using something like this
$original = 2;
$float = number_format($number, 2);
// echo $float = 2.00
I guess if you need to enforce that a float only has 2 decimals you could do something like the following.
$numbers = array(2.453, 3.35, 2.53, 1.636);
foreach($numbers as $number) {
if(strpos($number, '.') !== false) {
if(strlen($parts[1]) == 2) {
echo $number .' is valid!';
} else {
echo $number .' is NOT valid!';
}
}
}
The above is one way to accomplish this but there are many others. You could use array_map or array_filter and you could also use math such as the following
$numbers = array(2.453, 3.35, 2.53, 1.636);
$valid_numbers = array_filter($numbers, function($number) { return strlen($number) - strpos($number, '.');
function check_decimals($input, $number_of_decimals)
{
if(strlen(substr(strrchr((string)$input, "."), 1)) == $number_of_decimals)
{
return TRUE;
}
else {
return FALSE;
}
}
check_decimals("1.000", 2);
This may be a solution using preg_match_all
$re = "/^\\d+(?:\\.\\d{2})?$/m";
$str = "1.00\n13333.55\n1.000";
preg_match_all($re, $str, $matches);
echo '<pre>';
print_r($matches);
echo '</pre>';
REGEX: https://regex101.com/r/nB7eC4/1
CODE: http://codepad.viper-7.com/49ZuEa

How to remove zeroes at the end of decimal part of a float number?

I have in database product prices with 4 digits in decimal part, i.e;
4.5000
0.0050
5.0000
I want to show on the website these prices with minimum 2 decimal digits (without rounding), i.e;
4.50
0.005
5.00
I tried number_format, but it still leaves 4 digits in decimal part.
And also I need to use thousands separator on a base part of that number and own delimiter of decimal part.
How to do this?
function trimDecimalZero($num, $delim = ',', $tsep = ' ') {
#list($base, $decimals) = explode('.',
rtrim(number_format((float) $num, 4, '.', $tsep), '0'));
if (intval($decimals)) {
return sprintf('%s%s%s',
$base, $delim, strlen($decimals) < 2 ? $decimals .'0' : $decimals);
}
return sprintf('%s%s%02d', $base, $delim, $decimals);
}
$nums = [4.5000, 0.0050, 5.0000];
foreach ($nums as $num) {
var_dump(trimDecimalZero($num));
}
Result as expected;
string(4) "4,50"
string(5) "0,005"
string(4) "5,00"
Try with -
echo number_format('4.5000', 2);
Update
$v = (float)'0.0050';
$newV = explode('.', $v);
if(strlen($newV[1]) < 2) {
$v = number_format($v, 2);
}
echo $v;
For future reference, once again I modified my answer and yes, it outputs expected results:
function trimDecimalZero($number) {
$number += 0;
if(strlen(substr(strrchr($number, "."),1)) < 2) {
$number = sprintf("%0.2f", $number);
}
return $number;
}
echo trimDecimalZero(4.5000); //4.50
echo trimDecimalZero(0.00050); //0.00005
echo trimDecimalZero(5.0000); //5.00
Hope this would help future readers!
I guess that if it is for showing purposes, you could do something like this:
$number= 4.500000;
$number.= 'x';
$length = strlen($number);
$new_number = rtrim($number, '0x');
if (strlen($new_number) < $length) {
$new_number .= '0';
}
echo $new_number;

Categories