php number format with several rules - php

given a number and n, I want to format it in the following way:
if it's an integer(without any decimal point), just return it
if it has x decimal point, only show m decimal point where m is the minimum of x and n.
number_format can't do this, what would be the easiest way to achieve this?
a few examples:
input: number = 60, n=1, output: 60
input: number=60.0, n=0, output: 60
input: number = 60.0623, n=1, output: 60.0
input: number = 60.06, n=3, output: 60.06

Try this:
$number = 12345;
$maxdecimals = 5;
echo rtrim(rtrim(number_format($number,$maxdecimals),"0"),".");
This will trim off trailing zeroes, and the decimal point if there are only zeroes following it. In this case, you'll get 12,345.

the answer is
round($number,$maxdecimals)

Related

PHP Retain all decimals when using abs function

I'm using the abs function to get the positive value of a negative number as follows:
$totalTax = -4.50 ;
echo abs($totalTax);
which is working well except it is dropping the 0 and returns 4.5 instead of 4.50.
Not sure why it's doing this or what the best method to retain all digits when using the abs function to convert a negative number to a positive? I need the 2 decimals regardless if the cents value is 0 for importing into an accounting system which only accepts 2 decimals and not 1.
It's just because how PHP outputs leading/trailing zeros - trims them. Because there is infinite number of zeros after last non-zero number
e.g. echo 00000.1000000 will output 0.1
You should format your number to keep that leading and trailing zeros.
echo number_format($totalTax, 2, '.', '');
// -> 4.50
You can try with the number_format() function. There is no possibility to retain trailing 0 with using only the abs() function.
Here is code you try:
$totalTax = -4.50 ;
$total_sub = abs($totalTax);
echo number_format($total_sub, 2);

Round second digit after decimal to produce nice number

Need to round 30.61 to 30.60, Any built-in function for PHP to do this ?
If I understand your desired output correctly, that you only want to round the second decimal point, you can round with 1 decimal presicion, then use numer_format() to ensure you get the correct number of decimals.
$num = 30.61;
echo number_format(round($num, 1), 2);
round() documentation
number_format() documentation
Live demo
you can do this
$num = 3.61;
/*round to nearest decimal place*/
$test_number = round($num,1);
/* ans :3.6
format to 2 decimal place*/
$test_number = sprintf ("%.2f", $test_number);
/* ans : 3.60 */

php placement of the dot in a long number

I want to display a large number with a leading zero and a dot after.
The balance i want to display starts with 0.000000000000000000 ( 18 zeros after the dot ). This should be able to go up to 99.00000000000000000.( 17 zeros after the dot ).
I did a lot of trial and error but i just can't seem to get the dot in there. As far as for the zeros i got it working. What i have now is:
$leadingBalance = sprintf("%019d", $balance);
echo $leadingBalance;
This will display the correct balance but i need to place the dot in there. It means that if my balance has 17 or 18 numbers it should place the dot as 0.0000... If the balance has 19 numbers it should place the dot as 00.0000...
Whatever i try, how much i look up i can't figure it out.
For eg:
$n1 = 0;
$n2 = 99;
echo number_format($n1,18)."<br>";
echo number_format($n2,18)."<br>";
See the documentation for number_format: http://php.net/number_format
The functions parameters are:
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
So use:
number_format(1000000000000000, 2, '.', '');
Which means that you don't use any (= empty string) thousands separator, only a decimal point.
or if you just want padding of 19 zero after decimal point
just use
sprintf("%0.19f",$number);
or else
if u want a number always 20 digit without caring about whole no and decimal value than use str_pad()
eg:
$no = sprintf("%0.2f",100); //100.00
this will convert your no to decimal point with 2 digit after decimal now just pad some digit if require to make it 20 digit long
echo str_pad($no,20,"0"); //100.00(15 zero after this)
this will check no of digit available and pad 0 to make it 20 digit
for more ref:https://www.w3schools.com/php/func_string_number_format.asp
You are using %019d when you actually wants a float number, try this:
<?php
$format = '%0.19f';
$args = 9;
$result = sprintf ($format, $args);
//$result will be equal to 9.0000000000000000000
?>
<?php
$format = '%0.19f';
$args = 99;
$result = sprintf ($format, $args);
//$result will be equal to 99.0000000000000000000
?>
Edit:
Since it looks like you want your whole number to be equal to 20 digits only, you may try to do some math if number_format doesn't do your job. You can try something like:
<?php
$number = 999;
$number_length = strlen($number);
$format_len = 20 - $number_length;
$format = '%0.'. $format_len .'f';
$result = sprintf($format, $number);
?>

How to keep leading zeros when subtracting 2 numbers in PHP?

This:
$difference = 05-1;
results in
4
same if I do this:
$difference = 05-01;
is there a inbuilt way to subtract while keeping leading zeros? I know I can check to see if the difference has only 1 character or not and if so add a leading zero but was just wondering if there is a default way to get the result back with 0 already in it.
No I dont think PHP will natively keep the leading 0's unless its a float. In PHPs mind 4 is 4 not 04 tho 0.4 is 0.4
So if you need the leading 0 in ints lower the 10 pad it with str_pad():
<?php
$difference = (05-1);
echo str_pad($difference, 2, "0", STR_PAD_LEFT);//04
?>
<?php
$difference = 234;
echo str_pad($difference, 2, "0", STR_PAD_LEFT);//234
?>
If it's just a matter of outputting you can use printf() to add leading zeroes. The following:
<?php
printf("Result: %02d", 04-1);
?>
will output:
Result: 03
the %02d translates to fill with '0' (%0 2d) for 2 spaces (%0 2 d) and format as an integer (%02 d). A lot can be done with printf() to set precision, add leading characters, and use placeholders while outputting text.

Advanced Php Number Formatting

I want to have a PHP number formatted with a minimum of 2 decimal places and a maximum of 8 decimal places. How can you do that properly.
Update: I'm sorry, my question is say I have number "4". I wish for it to display as "4.00" and if I have "2.000000001" then it displays as "2.00" or if I have "3.2102" it will display as such. There is a NSNumber formatter on iPhone, what is the equivalent in PHP.
This formats the $n number for 8 decimals, then removes the trailing zero, max 6 times.
$s = number_format($n, 8);
for($i=0; $i<8-2; $i++) {
if (substr($s, -1) == '0')
$s = substr($s, 0, -1);
}
print "Number = $s";
Use sprintf() to format a number to a certain number of decimal places:
$decimal_places = 4;
$format = "%.${decimal_places}f";
$formatted = sprintf($format,$number);
I don't understand why you would want to display numbers to an inconsistent degree of accuracy. I don't understand what pattern you're trying to describe in your comment, either.
But let us suppose that you want the following behaviour: you want to express the number to 8 decimal places, and if there are more than 2 trailing zeroes in the result, you want to remove the excess zeroes. This is not much more difficult to code than it is to express in English. In pseudocode:
$mystring = string representation of number rounded to 8 decimal places;
while (last character of $mystring is a 0) {
chop off last character of $mystring;
}
Check the number format function:
<?php
$num = 43.43343;
$formatted = number_format(round((float) $num, 2), 2);
?>
http://php.net/manual/en/function.number-format.php
Using preg_match just get the zero ending with and then rtim it
<?php
$nn = number_format(10.10100011411100000,13);
preg_match('/[0]+$/',$nn,$number);
if(count($number)>0){
echo rtrim($nn,$number[0]);
}
Hope it will help you.

Categories