Remove useless 0 after 3 digits and round after 6 digit - php

I use the floatval() function to remove useless 0s, but I want to keep at least 3 significant numbers. Like if I have 0.1800000 I want to show 0.180 and if I have 1.8454214 I want to show 1.845421. How can I do a round after 6 digits and remove useless 0s after 3 digits?
$value = 1.80000;
$value = floatval(round($value,6));
echo $value; //I get 1.8
Or if I have
$value = 1.84542146543;
$value = floatval(round($value,6));
echo $value; //I get 1.845421
And this works fine, but not if I've got a lot of 0s.
I always need minimum 3 decimal, but it can be more.

Try with the below code
$value = 1.80000;
$value = floatval(round($value,6));
$valArr = explode('.', $value);
if(isset($valArr[1])){
if(strlen($valArr[1]) < 3){
$valArr[1] = str_pad($valArr[1], 3, "0", STR_PAD_RIGHT);
$value = $valArr[0].'.'.$valArr[1];
}
else{
$value = floatval(round($value,6));
}
}
echo $value;
It will work if you want to print the 0s in your web page.

Use a combination of floor and sprintf to truncate the float to a string with 3 decimal places. Then use max to compare it with the rounded float. PHP will compare the values numerically, returning the first parameter (padded with zeros) if they are numerically the same, only returning the second value if it is numerically greater (ie there is a digit larger than 0 after the third decimal place).
$value = max(
sprintf("%.3f", floor($value * pow(10, 3)) / pow(10, 3)),
round($value, 6));

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

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 to integer

I want to round a number and I need a proper integer because I want to use it as an array key. The first "solution" that comes to mind is:
$key = (int)round($number)
However, I am unsure if this will always work. As far as I know (int) just truncates any decimals and since round($number) returns a float with theoretically limited precision, is it possible that round($number) returns something like 7.999999... and then $key is 7 instead of 8?
If this problem actually exists (I don't know how to test for it), how can it be solved? Maybe:
$key = (int)(round($number) + 0.0000000000000000001) // number of zeros chosen arbitrarily
Is there a better solution than this?
To round floats properly, you can use:
ceil($number): round up
round($number, 0): round to the nearest integer
floor($number): round down
Those functions return float, but from Niet the Dark Absol comment: "Integers stored within floats are always accurate, up to around 2^51, which is much more than can be stored in an int anyway."
round(), without a precision set always rounds to the nearest whole number. By default, round rounds to zero decimal places.
So:
$int = 8.998988776636;
round($int) //Will always be 9
$int = 8.344473773737377474;
round($int) //will always be 8
So, if your goal is to use this as a key for an array, this should be fine.
You can, of course, use modes and precision to specify exactly how you want round() to behave. See this.
UPDATE
You might actually be more interested in intval:
echo intval(round(4.7)); //returns int 5
echo intval(round(4.3)); // returns int 4
What about simply adding 1/2 before casting to an int?
eg:
$int = (int) ($float + 0.5);
This should give a predictable result.
Integers stored within floats are always accurate, up to around 253, which is much more than can be stored in an int anyway. I am worrying over nothing.
For My Case, I have to make whole number by float or decimal type
number. By these way i solved my problem. Hope It works For You.
$value1 = "46.2";
$value2 = "46.8";
// If we print by round()
echo round( $value1 ); //return float 46.0
echo round( $value2 ); //return float 47.0
// To Get the integer value
echo intval(round( $value1 )); // return int 46
echo intval(round( $value2 )); // return int 47
My solution:
function money_round(float $val, int $precision = 0): float|int
{
$pow = pow(10, $precision);
$result = (float)(intval((string)($val * $pow)) / $pow);
if (str_contains((string)$result, '.')) {
return (float)(intval((string)($val * $pow)) / $pow);
}
else {
return (int)(intval((string)($val * $pow)) / $pow);
}
}
Round to the nearest integer
$key = round($number, 0);

php currency take

I need to know how to take
10.25 and turn it to 1025
basically it needs to remove full stop from any number for e.g.
1500.25 it should be 150025
$number = str_replace('.','',$number);
if the currency is a float: multiply with 100 (and cast the result to int).
$currency = 10.25;
$number = (int)($currency * 100); //1025
note that this solution will only get the first two decimals saved - if you have a number like 10.123, the 3 will simply be cut off without rounding.
Floating-point arithmetic is by it's definition not exact. Therefore it's worthwhile to NOT cast the value to a float if it's a string, and avoid casting it into a string if it's a float.
Here's a function which takes care to check the value type:
function toCents($value) {
// Strings with a dot is specially handled
// so they won't be converted to float
if (is_string($value) && strpos($value, '.') !== false) {
list($integer, $decimals) = explode('.', $value);
$decimals = (int) substr($decimals . '00', 0, 2);
return ((int) $integer) * 100 + $decimals;
// float values are rounded to avoid errors when a value
// like ".10" is saved as ".099"
} elseif (is_float($value) {
return round($value * 100);
// Other values are strings or integers, which are cast
// to int and multiplied directly.
} else {
return ((int) $value) * 100;
}
}
if you want replace one character only, use strtr instead str_replace
$number = str_replace('.','',$number);
and
$number = strtr($number, array('.', ''));
same output but strtr is better.

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

Categories