Why trim zeros from decimal part php not accurate for .00? - php

I have this float value 1290.00 and I would like to trim the zeros on the right in the cleanest way to get 1290, but Why I got 129 if using trim function?
Code:
<?php
$var = '1290.00';
printf ("value: %s -> %s\n", $var, trim($var, '.00'));
The output:
value: 1290.00 -> 129
I have seen different solutions to it by not using trim function, but why is trim not working? I also tried with GoLang and got the same behavior.

Trim removes characters from the end, individually, not as a phrase. It removes all found characters until it can't find any more in the list. So it removes the 0, the 0, the period, then the 0. In this case, I would recommend either round or number_format
number_format($var, 0, '', ''); // 1290

trim doesn't work like that. You only specify the characters you want to trim once, and two periods are used to specify a range. It will then trim all of those characters from the end.
A more efficient method might be intval($var)

Depending on your usage, note that number_format() also rounds the value (see the first example of the documentation). If you need to truncate the number you could use floor():
number_format(1.9, 0, '', ''); // string(1) "2"
floor(1.9); // 1

Related

floatval causes the digits after the thousand sep ',' to be erased

floatval('19500.00');
returns 19500 ;
however
echo floatval('19,500.00');
returns 19 ;
this could've really given me a big problem it was good that I've noticed :D ... is there some reason for that behavior or it's just a bug ... should all values be number_formatted before ouput?
You put that value in single quotes, so it's not treated as a numerical value, but as a string.
Here's php.net's explanation what happens to strings with floatval (from http://php.net/manual/en/function.floatval.php):
Strings will most likely return 0 although this depends on the
leftmost characters of the string.
Meaning: The leftmost characters of the string in your case is 19 - that's a numerical value again, so the output is 19.
Decimal and thousands separator symbols are defined by current locale used in your script.
You can set default_locale in php.ini globally, or change locale in your script on the go: http://php.net/manual/en/function.setlocale.php
Different locales have different separators. To check, which is the current separator symbol, you can use localeconv function: http://us2.php.net/manual/en/function.localeconv.php
$test = localeconv();
echo $test['decimal_point'];
#.
echo $test['thousands_sep'];
#,
But actually no one can make this function work properly with all these commas and dots, so the only solution is to clean the input removing everything except "." and numbers by regexp or str_replace:
echo floatval(preg_replace("/[^0-9\.]/", "", '19,500.00'));
#19500
echo floatval(str_replace(",", "", '19,500.00'));
#19500

format a floating number using PHP

I want to format a floating number, like this :
Input : 1.7
output : 01.70
I have already tried below function.
sprintf("%02.02f", 1.7);
Please help.
Try:
sprintf('%05.2f', 1.7);
Explanation
This forum post pointed me in the right direction: The first number does neither denote the number of leading zeros nor the number of total charaters to the left of the decimal seperator but the total number of characters in the resulting string!
Example
sprintf('%02.2f', 1.7); yields at least the decimal seperator "." plus at least 2 characters for the precision. Since that is already 3 characters in total, the %02 in the beginning has no effect. To get the desired "2 leading zeros" one needs to add the 3 characters for precision and decimal seperator, making it sprintf('%05.2f', 1.7);
Try this
sprintf('%05.2f', 1.7);
Are you tried with str_pad()? It's for strings, and that's what you need, because $var = 001 is an octal and $var = "001" is a string.
$input = 1.7;
$output = str_pad($input, "0", 2, STR_PAD_BOTH)

Combined width sprintf

I have two strings I want to combine and have not exceed a certain width.
$string = sprintf("%4(%s %s)", $s1, $s2);
//s1 s
Notice how the combined %s %s did not exceed a width of 4.
How can I do this with sprintf?
Thanks!
You probably need to add more detail to your question - what do you want to happen if the fields are longer than 3 characters (4 - one space)?
But maybe this is what you want:
sprintf("%.4s", "$s1 $s2");
That will output the combined string "$s1 $s2", pruned to 4 characters. Of course substr would do the same, this might be useful in the context of a longer format string.
To be honest I hadn't realised before that the precision specifier (. followed by number) could be used with %s.
Im not sure how to do so with sprintf but you can use substr() to do so;
$string = substr("$s1 $s2",0,4);
This should return the same result

php substr and text manipulation

I would like to take this data:
questionX
Where X is any number from zero to infinity.
And subtract the text question from the field, and save just the number.
I was toying with substr($data, 0, 8) but haven't gotten it to work right, can somebody please give me a suggestion? Thanks so much.
The manual for substring http://php.net/manual/en/function.substr.php
indicates that the function takes three arguments: the string, the start, and the length. Length is optional. If omitted, substr will return the rest of the string starting from 'start'. One way to get your X value would be to do something like this:
$theNumber = substr($data, 8);
It look like you don't' really understand what substr does. Substr does not 'subtract' part of the string from itself. It returns the part of the string that you specify with the start and length paramaters
Try this
$number = str_replace("question", "", $string);

Trim any zeros at the beginning of a string using PHP

Users will be filling a field in with numbers relating to their account. Unfortunately, some users will have zeroes prefixed to the beginning of the number to make up a six digit number (e.g. 000123, 001234) and others won't (e.g. 123, 1234). I want to 'trim' the numbers from users that have been prefixed with zeros in front so if a user enters 000123, it will remove the zeroes to become 123.
I've had a look at trim and substr but I don't believe these will do the job?
You can use ltrim() and pass the characters that should be removed as second parameter:
$input = ltrim($input, '0');
// 000123 -> 123
ltrim only removes the specified characters (default white space) from the beginning (left side) of the string.
ltrim($usernumber, "0");
should do the job, according to the PHP Manual
$number = "004561";
$number = intval($number, 10);
$number = (string)$number; // if you want it to again be a string
You can always force PHP to parse this as an int. If you need to, you can convert it back to a string later
(int) "000123"
You can drop the leading zeros by converting from a string to a number and back again. For example:
$str = '000006767';
echo ''.+$str; // echo "6767"
Just multiply your number by zero.
$input=$input*1;
//000000123*1 = 123

Categories