I would like to format numbers, so numbers woul format like this:
1=1
10=10
100=100
1000=1,000
10000=10,000
100000=100,000
1000000=1,000,000
I think it can be done with number_format(), but right now I`m having a problem, so if the number is 35679 it shows 35,679,000.
If you want 35679 to show up as 35,679:
number_format(35679,0,'',',');
First parameter is the input number. Second is the amount of decimals. Third is the decimal separator (not needed without decimals).
Last is the thousands separator.
(You probably set the number of decimals to 3)
Please see THIS for a complete explanation of number_format().
For example you would need number_format($number, 0) if the default settings are present or number_format($number, 0, '.', ',') for comma to be used as thousand seperator.
Related
I am working on a PHP-script that handles monetairy amounts, and therefore needs to be exact with 2 decimals. To do this, I convert the user-input to a number by multiplying it with 100, and then casting it to int. This works fine, untill I recently discovered a number that increases by 1 when cast to int.
the malfunctioning code:
$number = (int)(str_replace(',','.',$_POST["input"])*100);
The number that gives problems is 2509,22 (I live in the Netherlands, so we use comma's for decimals, hence the str_replace in the above line of code).
This value creates the integer $number 250921, which is obviously 1 too low.
I know that int has limits, but this number is well within those limits as far as I'm aware...
When you multiply the string by 100 you get a float and its representation is not always what you expect, in this case 250921.99999999997. See it with:
echo serialize(str_replace(',','.','2509,22')*100);
Then you cast to an integer which trucates the fraction to get 250921. See Is floating point math broken?.
The solution would be to remove the comma and use as is and optionally cast to an integer:
$number = (int)str_replace(',', '', '2509,22');
For the issue of users entering too many fractional numbers, you should either use two inputs, one for whole number and one for fraction and/or restrict/validate that the inputs are correctly formatted. However, you can format the number first:
echo $number = (number_format(str_replace(',', '.', '2509,22'), 2, '.', '')*100);
You can use regex to match the int and zero - two decimals.
This will not do any conversions and nothing is multiplied or casted.
It will be treated as a string and nothing changes but the number of decimals.
$input = "2509,2222222";
// Regex number comma number (zero - two)
Preg_match("/(\d+),*(\d{0,2})/", $input, $m);
Unset($m[0]); // remove full match
Echo implode("", $m); // implode parts
https://3v4l.org/MjcYV
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)
Is there a number_format alternative in PHP that allows me to chose thousands and decimal separator, while keeping the number of decimals? E.g. something like this:
number_format_alternative( '1234.617', ',', '.' );
>1 234,617
but
number_format_alternative( '120.0', ',', '.' );
>120.0
I realize that I could achieve almost the same thing, by using a ridiculously high number of decimals, and trimming all zeros from the right, though the second example would then look like:
number_format_alternative( 120.0, ',', '.' );
>120
edit: This is what I ended up doing:
function numberOfDecimals( $number ) {
return strlen(strstr(rtrim(sprintf('%.10F', $number), '0'), '.'))-1;
}
Since you are inputting the number to the function as a string you could use a regular expression to see how many digits are after the decimal point, represented by '.' in this case, and then execute number_format with the $decimals parameter set to the number you just calculated.
One regular expression that would work would be \.\d+ and then minus 1 off the length to find the decimals number, you could use a look behind how ever I think the performance would be worse. Some testing may be needed and I am sure there will be other regular expressions that would work.
I have been handling long numbers in PHP. Like the following examples.
12.020000
12.000000
To get rid of trailing zeros and the decimal point I have been using the following inside a function.
return rtrim(rtrim($str, "0"),".");
So the above turns out like.
12.02
12
It was a bit short sighted as when 1000 gets entered it gets turned into 1.
Can someone please help me with the code to remove trailing zeros after the decimal point only?
Bonus points if the code removes the decimal place but I can always feed it into rtim($str,".").
EDIT: To be clear, I am stripping the decimal place and zeros only when displaying to the screen. Also casting to float is not an option as I also handle numbers like 0.00000001 which come out like 1.0e-9 sort of thing.
Why are you using string to hold numbers? Cast it to float and it'll solve your problem.
$string = '12.020000';
$number = (float) $string; // will be 12.02
Then, if you want to use it as string (but why?)
$string = (string) $number;
The thing that perplexes me about your question is that extra zeros won't be included in a number variable without intentionally adding them with number_format. (This may be why someone down-voted it).
Normally you don't want to use string functions (meant for text) on variables that hold numbers. If you want to round off a number, use a function like round.
http://php.net/manual/en/function.round.php
There's also number_format, which can format numbers by adding zero padding: (it doesn't actuall round, just trims off excess numbers).
http://php.net/manual/en/function.number-format.php
Since your zeros are appearing, it's likely that you simply need to multiple the variable by 1, which will essentially convert a string to a number.
Good luck!
Ok say I have my phone numbers stored in my table as:
"0008675309"
I obviously wouldn't want to display it just like that, I'd want to format it when I call it as:
(000)867-5309
Would it be better to store it in the database with a delimiter such as / - or . So that I can split it later? Or is it possible to split it by the number of characters?
The performance cost and code to process a phone number in any of those formats is simple, so it's really up to your preference. To answer your question, it is very easy to grab the first three characters, the next three, and the last four using for example, substr function.
Here is a one liner that does what you want:
$phone = preg_replace('^(\d{3})(\d{3})(\d{4})$', '($1)$2-$3', $phone);
As a added bonus it won't change the format if the input format doesn't match (international numbers).
If you are only storing North American phone numbers (10 digits), then as #mellamokb noted, you're ok either way. If you may be storing international numbers, you should capture as much detail as you can early on (if possible) since it might be hard to know how to punctuate the number later on.
use preg_split with PREG_SPLIT_NO_EMPTY
The other answers are perfectly correct. In case you wanted the actual code for it, I think the following should do the trick (the indexes may be off by one oops!):
$phone_number="0008675309"
$phone_number=substr_replace($phone_number, "(", 0, 0);
$phone_number=substr_replace($phone_number, ")", 4, 0);
$phone_number=substr_replace($phone_number, "-", 8, 0);