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);
?>
Related
After a few calculations I get:
$int = 14.285714285714;
How can I take only the first four digits? Expected output: 14.28
Doing this with string functions is absolutely the wrong way to go about this, and these nearly identical answers look pretty spammy. If you want to round a number, round a number!
$int = round(14.285714285714, 2);
To truncate (as opposed to rounding), floor is the correct function in PHP:
$int = floor(14.285714285714 * 100) / 100;
Both work without any type conversions or casting.
Also note that a number with decimal places is categorically not an integer.
use substr function
$int = 14.285714285714;
echo substr($int, 0, 5);
$newint = (float)substr($int, 0, 5);
IF you want to round the number you can use
round($int, 2);
OUTPUT WILL BE : 14.29
LINK HOW TO ROUND
Try number format,
string number_format ( float $number [, int $decimals = 0 ] )
so
$int = 14.285714285714;
$small = (float)number_format ( $int ,2,'.', '' ); //gets rid of the "," for thousand separator
http://us2.php.net/manual/en/function.number-format.php
floor(100 * 14.285714285714) / 100
14.28
$sum = 000000000117800;
$sum = number_format($sum, 2, ".", ".");
I am looking for the output 1 178.
The sum is always a length of 15. Like assigned above. The sum could also be:
000000001117800;
Then it would be
11 178
and so on.
The last two defines the decimals: So for example
000000000117805;
would be
1 178,05
My code above gives me: 79.00 though...
I am wondering if I could solve this perhaps with ltrim, but perhaps there is another more better way ?
Your code is correct, you simply have to use a string
$sum = "000000000117800";
echo number_format($sum, 2, ".", ".");
prints ( http://ideone.com/534ATu )
117.800.00
Although, you have to divide by 100 to get the fractional part right
$sum = "000000000117800";
echo number_format($sum / 100, 2, ".", ".");
which prints ( http://ideone.com/A5LFpS )
1.178.00
the problem is when you assign
$sum = 000000000117800;
it is already being converted to 79 (as an octal value of $sum) and you cannot do anything about it.
so why do strings work? Because number_format expetcs float as a first argument, so PHP performs conversion from string to float, which ignores leading 0's. As a result we have 117800 which we have to further divide by 100 to get decimals right, then we can use number_format for nice display, or simply do (http://ideone.com/IeBCmF)
$sum = "000000000117800";
echo $sum / 100;
and get
1178
and for
$sum = "000000000117805";
echo $sum / 100;
we get
1178.05
as requested
One final remark about number_format - to get desired formatting you should use
number_format( $value, 2, ',', ' ')
so (http://ideone.com/yDQXde)
$sum = "000000000117805";
echo number_format( $sum / 100, 2, ',', ' ');
prints
1 178,05
It looks like you need to remove the leading 0's before hand. I went to http://writecodeonline.com/php/ and ran the code
$sum = 000000000117800;
$sum = number_format($sum, 2, ",", ".");<br>
echo $sum;
Then ran the code
$sum = 117800;
$sum = number_format($sum, 2, ",", ".");
echo $sum;
and it worked, it;s like the leading 0's are causing the numbers to be interpreted as another format (OCTAL as a commenter said) and not decimal.EDIT:
As a solution try ltrim before running the number_format to remove leading0'shttp://php.net/manual/en/function.ltrim.php string ltrim ( string $str [, string $charlist ] )
Strip whitespace (or other characters) from the beginning of a string.
That is because you number is treated like octal because of leading zero.
0117 in octal system is exactly 79 in decimal system.
Your initial value 000000000117800 is reduced to 0117 because 8 is not octal digit, so PHP cuts the last digits of your number.
Your output is 79 for two reasons:
Numbers starting with a leading zero are octal, octal 0117 is 7*1 + 1*8 + 1*64 == 79
PHP is broken, and will blindly ignore invalid characters at the end
Why does your number contain those leading zeros? A number has no concept of "length" - that's a property of it's string representation.
The number is 13911392101301011 and regardless of using sprintf or number_format i get the same strange result.
sprintf('%017.0f', "13911392101301011"); // Result is 13911392101301012
number_format(13911392101301011, 0, '', ''); // Result is 13911392101301012
sprintf('%017.0f', "13911392101301013"); // Result is 13911392101301012
number_format(13911392101301013, 0, '', ''); // Result is 13911392101301012
As you actually have the number as a string, use the %s modifier:
sprintf('%s', "13911392101301011"); // 13911392101301011
Note that PHP is using a signed integer internally. The size depends on your system.
32bit system:
2^(32-1) = 2147483648
64bit system:
2^(64-1) = 9223372036854775808
-1 because 1 bit is reserved for the signage flag.
Since you are dealing with large numbers here, you may want to keep them as strings and perform numerical operation on the string values using BCMath functions.
$val = "13911392101301011";
echo $val; // 13911392101301011
echo bcadd($val, '4'); // 13911392101301015
echo bcmul($val, '2'); // 27822784202602022
You can do easily this way :-
ini_set("precision",25); // change 25 to whatever number you want or need
$num = 13911392101301011;
print $num;
Documentation states that $number in number_format is float so there is explicit typecast. Equivalent would look like this:
sprintf('%017.0f', (float) "13911392101301011");
Float is precise to around 14 digits and your number has 17 digits.
Your number_format call is setting the . and , to blank
string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
try this:
number_format(13911392101301011, 0, '.', ',');
How can I separate a number and get the first two digits in PHP?
For example: 1345 -> I want this output=> 13 or 1542 I want 15.
one possibility would be to use substr:
echo substr($mynumber, 0, 2);
EDIT:
please not that, like hakre said, this will break for negative numbers or small numbers with decimal places. his solution is the better one, as he's doing some checks to avoid this.
First of all you need to normalize your number, because not all numbers in PHP consist of digits only. You might be looking for an integer number:
$number = (int) $number;
Problems you can run in here is the range of integer numbers in PHP or rounding issues, see Integers Docs, INF comes to mind as well.
As the number now is an integer, you can use it in string context and extract the first two characters which will be the first two digits if the number is not negative. If the number is negative, the sign needs to be preserved:
$twoDigits = substr($number, 0, $number < 0 ? 3 : 2);
See the Demo.
Shouldn't be too hard? A simple substring should do the trick (you can treat numbers as strings in a loosely typed language like PHP).
See the PHP manual page for the substr() function.
Something like this:
$output = substr($input, 0, 2); //get first two characters (digits)
You can get the string value of your number then get the part you want using
substr.
this should do what you want
$length = 2;
$newstr = substr($string, $lenght);
With strong type-hinting in new version of PHP (> PHP 7.3) you can't use substr on a function if you have integer or float. Yes, you can cast as string but it's not a good solution.
You can divide by some ten factor and recast to int.
$number = 1345;
$mynumber = (int)($number/100);
echo $mynumber;
Display: 13
If you don't want to use substr you can divide your number by 10 until it has 2 digits:
<?php
function foo($i) {
$i = abs((int)$i);
while ($i > 99)
$i = $i / 10;
return $i;
}
will give you first two digits
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.