Is it possible to separate last digits in Php? - php

I have a string value which size 11(2): 00000700000
I want to convert this string to decimal. I clean leading zeros with ltrim function and then put comma at the end of the value with the function substr_replace:
ltrim(substr_replace( '00000700000', '.', -2, 0), '0')
The expected result is:
7000.00
Are there any cleaner way to separate last two digits with dot and convert this string to decimal?

You can simply cast that string to int and divide by 100:
intval('00000700000') / 100; // 7000
If you want that same number formatted, use format_number():
number_format(num: $result, decimals: 2, thousands_separator: '') // 7000.00
Example

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

Number Range generator using max and min length with leading zeroes [duplicate]

This question already has answers here:
Formatting a number with leading zeros in PHP [duplicate]
(11 answers)
Closed 3 years ago.
I have min and max range of number need to generate number between two range with leading zeroes.
Example:
$min:000001;
$max:999999;
$uname=mt_rand($min,$max);
output:
$uname=2;
if generate number of two digit then append four zeroes, how can i set dynamic append zeroes of starting of string.
expected output: $uname=000002;
if
$uname = 20;
then
expected output:
$uname=000020;
Just use the function sprintf(). You can pass a format-string and the number you would like to output to this function.
Here is a small example:
$x = 7;
$y = 13;
sprintf("%03d", $x); // 007
sprintf("%03d", $y); // 013
sprintf("%02d", $x); // 07
sprintf("%02d %02d", $x, $y); // 07 13
The "d" in the format-string is standing for an integer number, the "03" is caring about filling 3 places.
The two last lines are showing examples of how to use this function to fill 2 places and to output more than one numbers at once.
Another function that could be interesting for you is str_pad() - this function is working with strings instead of numbers.
we can use it like it is shown in the following example:
$str = 'abc';
echo str_pad($str, 5, '.'); // '..abc'
echo str_pad($str, 5, '.', STR_PAD_RIGHT); // '..abc'
echo str_pad($str, 5, '.', STR_PAD_LEFT); // 'abc..'
echo str_pad($str, 5, '.', STR_PAD_BOTH); // '.abc.'
echo str_pad($str, 8, '. '); // '. . .abc'
echo str_pad($str, 8); // ' abc'
The function takes a string as the first parameter and the second parameter is a value, how long the string should be.
The third, optional parameter is the character or the set of characters to be used for filling. If you omit this parameter, a blank is used. If the number of characters for filling is not fitting, the filling characters are just cut, so that they come to the right length.
The fourth and last parameter specifies whether the string should be filled right justified (STR_PAD_RIGHT), left justified (STR_PAD_LEFT) or centrally (STR_PAD_BOTH). If you omit this parameter, the function uses a right alignment.

Prevent number_format from rounding numbers - add commas and keep the decimal point - PHP

Number format adds the commas I want but removes the decimals.
echo number_format("1000000.25");
This returns 1,000,000
I want it to return 1,000,000.25
I need both the commas and the decimals, without any number rounding. All my values are decimals. They vary in length.
Do I have to use something other than number format?
In case what you meant by they vary in length is related to the decimal part, take a look at this code:
function getLen($var){
$tmp = explode('.', $var);
if(count($tmp)>1){
return strlen($tmp[1]);
}
}
$var = '1000000.255555'; // '1000000.25'; // '1000000';
echo number_format($var, getLen($var));
Some tests
Output for 1000000.255555:
1,000,000.255555
Output for 1000000.25:
1,000,000.25
Output for 1000000:
1,000,000
It counts how many chars there are after the . and uses that as argument in the number_format function;
Otherwise just use a constant number instead of the function call.
And some reference...
From the manual -> number_format():
string number_format ( float $number [, int $decimals = 0 ] )
And you can see in the description that
number
The number being formatted.
decimals
Sets the number of decimal points.
And a bit more:
[...]If two parameters are given, number will be formatted with decimals
decimals with a dot (".") in front, and a comma (",") between every
group of thousands.
$number = '1000000.25';
echo number_format($number, strlen(substr(strrchr($number, "."), 1)));
Explanation:
Number Format takes a second parameter which specifies the number of decimal places required as pointed out in the docs. This Stack overflow answer tells you how to get the number of decimal places of your provided string
The docs for number_format() indicate the second parameter is used to specify decimal:
echo number_format('1000000.25', 2);
Ref: http://php.net/manual/en/function.number-format.php

Convert strings to numbers without losing decimals

I'm developing a map and I have to save this parameters on Parse database:
lat.: 20.6350 . Long: -103.5334
The problem is when i convert them into numbers, that function converts 20.6350 to 20.635. ¿What can I do in order tu preserve the last zero?
You should specify the sig figs and they will display properly.
$lat = "20.6350";
$lng = "-103.5334";
print number_format($lat, 4); // 4 sig figs
print number_format($lng, 4);
See http://php.net/number_format for additional formatting info
UPDATE
Based on your comments above, seems the string you're pulling varies in length, correct?
Why not just get the amount of sig figs after the decimal then use that as the second argument in number_format()? I'm sure there is a more appropriate way to handle, but this would work I believe.
// Calculate sig figs
$length = strlen($lng) - (stripos($lng, '.') + 1);
number_format($lng, $length);
or in one line
number_format($lng, strlen($lng) - (stripos($lng, '.') + 1));
if you want the numbers with four decimals in your database you could use the Decimal type. Under length you could enter 6,4 representing maximum of 6 digits in total and 4 digits behind the point.
If you want to display the number in PHP you could use the number_format() function
echo number_format($longitude, 4);

In PHP, how do I add to a zero-padded numeric string and preserve the zero padding?

If I have a variable in PHP containing 0001 and I add 1 to it, the result is 2 instead of 0002.
How do I solve this problem?
$foo = sprintf('%04d', $foo + 1);
It would probably help you to understand the PHP data types and how they're affected when you do operations to variables of various types. You say you have "a variable in PHP say 0001", but what type is that variable? Probably a string, "0001", since an integer can't have that value (it's just 1). So when you do this:
echo ("0001" + 1);
...the + operator says, "Hm, that's a string and an integer. I don't know how to add a string and an int. But I DO know how to convert a string INTO an int, and then add two ints together, so let me do that," and then it converts "0001" to 1. Why? Because the PHP rules for converting a string to an integer say that any number of leading zeroes in the string are discarded. Which means that the string "0001" becomes 1.
Then the + says, "Hey, I know how to add 1 and 1. It's 2!" and the output of that statement is 2.
Another option is the str_pad() function.
$text = str_pad($text, 4, '0', STR_PAD_LEFT);
<?php
#how many chars will be in the string
$fill = 6;
#the number
$number = 56;
#with str_pad function the zeros will be added
echo str_pad($number, $fill, '0', STR_PAD_LEFT);
// The result: 000056
?>

Categories