How to keep leading zeros when subtracting 2 numbers in PHP? - 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.

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

Looking for a PHP smart format number

I am looking for a solution for a smart number formatting in PHP.
For example we have 2 numbers below and we need 4 digits after decimal:
1.12345678
0.00002345678
Using normal number formatting, here are the results:
1.1234 // Looking good
0.0000 // No good
Can we make it keep going until there are 4 non-zero digits? If it can return 0.00002345, perfect!!!
Many thanks!!!
Might be overkill and the pattern could be optimized, but for fun; get optional 0s AND 4 NOT 0s after the .:
preg_match('/\d+\.([0]+)?[^0]{4}/', $num, $match);
echo $match[0];
To round it we can get 5 digits after the 0s and then format it to the length of that -1 (which will round):
preg_match('/\d+\.([0]+?[^0]{5})/', $num, $match);
echo number_format($match[0], strlen($match[1])-1);
For $num = '1234.000023456777'; the result will be 1,234.00002346 and the $matches will contain:
Array
(
[0] => 1234.000023456
[1] => 000023456
)
So this is the code I made to slove this:
$num = 0.00002345678;
$num_as_string = number_format($num,PHP_FLOAT_DIG,'.','');
$zeros = strspn($num_as_string, "0", strpos($num_as_string, ".")+1);
echo number_format($num, (4+$zeros), '.', '');
It converts the float number to a string, checks how many zeros exist after the decimal point and then does a number format with the extra zeros accounted for.
Note that it may break if your float is too big, you can change PHP_FLOAT_DIG to a number larger that may fix that.

Minus value using php [duplicate]

This question already has answers here:
How to pad single-digit numbers with a leading 0
(7 answers)
Closed 11 months ago.
I have the value as $title =10 and I want to minus it with 01.So my code is:
echo $minus = round(($title - 01),2);
I want the result $minus = 09 but this code not like this it still have the result $minus=9. Anyone help me please,Thanks.
The problem is that PHP is not strongly typed, and round() returns a number, which automatically has the leading zero stripped. Try:
$minus = "0" . round(($title - 01),2);
PHP is evaluating your 0-prefixed numbers to their base value -- 04 and 01 are 4 and 1 respectively.
If you want them to be output with a leading 0, try using a number formatter, or string padding or simply append them to the string, "0"
What's happening is that round() returns an integer. Which means it won't have any 0's before it. If you want it to return 0's before it, try
str_pad(round(($title - 1), 2), 2, "0");
That will make it always append a 0 before the number if it's only 1 number, but if it's 10 or 15 or something, it won't append a 0
echo str_pad(intval($title) - 1, 2, "0", STR_PAD_LEFT);
This will pad your result with a 0 if the result is only one digit; otherwise, it will not pad. For a leading zero always, you can replace the 2 with strlen($title)
Try this..
$i=04-01;
echo sprintf('%02s', $i);

printf formatting with php and integer values

I was trying to use printf for formatting but I realized that when I use %d, I can't use 0 for the padding specifier with - alignment. Here is what i'm trying to do:
$a = sprintf("%04d",5);
$b = sprintf("%'1-4d",5);
$c = sprintf("%0-4d",5);
$d = sprintf("%0-4s",5);
var_dump($a);//outputs 0005
var_dump($b);//outputs 5111
var_dump($c);//outputs 5(and 4 spaces) why not 5000?
var_dump($d);//outputs 5000
I think PHP is trying to think for you here.
If you right-pad 5 with four 0 characters, how would you be able to tell the difference between that and 50000? Or between 5 right padded with four 0 characters and 50 right padded with three 0 characters?
I don't have PHP handy to test, but what if you tried to use the format "%'0-4d" to convince it to do what you want?

Rounding decimals in PHP

I want to display a number as a winning percentage, similar to what you would see on ESPN baseball standings. If the user has no losses, I would like the percentage to read 1.000. If the user has no wins, I would like it to read .000. If the user has a mix of wins and losses, I would like to display .xyz, even if y or y and z are 0's.
This code gets me no trailing 0's, and also a 0 before the decimal (0.4 instead of .400, 0.56 instead of .560):
$wpct1 = $wins / ($wins + $losses);
if($wpct1 == 1){$wpct = '1.000';}else{$wpct = round($wpct, 3);}
This code gets the initial 0 befoer the decimal out of there, but still no trailing zeroes (.4 instead of .400):
$wpct1 = $wins / ($wins + $losses);
if($wpct1 == 1){$wpct = '1.000';}else{$wpct = substr(round($wpct, 3), 1, 4);}
This second solution is getting me closer to where I want to be, how would I go about adding the trailing 0's with an additional piece of code (one or two trailers, depending on the decimal), or is there another way to use round/substr that will do it automatically?
$wpct = ltrim(number_format($wins / ($wins + $losses), 3), '0');
This formats the number the three digit after the decimal point and removes any leading zeroes.
See number_format and ltrim for further reference.
sprintf('%04d',$wpct1);
Will print leading zeros
You need
number_format($wpct, 3)
You could use str_pad() to add trailing zeros like this:
if($wpct1 == 1){$wpct = '1.000';}else{$wpct = str_pad(substr(round($wpct, 3), 1, 4), 3, '0');}
sounds like number_format is what you're looking for.
Have a look at sprintf()
$x = 0.4;
echo sprintf("%01.3f", $x);
You can use php's built in number_format

Categories