Number formatting in PHP

Number formatting in PHP

OK while coding numbers are almost always there. Bit it stat, some calculation, rate finding … a lot is on numbers.
Saying so, we might want to beautify our numbers on displaying or storing or making them an input for another usage or we just want it.
PHP has the function number_format() for this usage: this accepts up to 4 parameters where we can supply either one, two or four of them.

lets have this number 456234.3451678 as a result of some calculation.
$number = 456234.3451678;
Taking the integral part:
we can do this in different methods
1. casting it to integer:

(int)$number;

2. using built-in function:

number_format($number); // output -> 456,234

3. using regex:

 
        $pattern="/.d*/";
        $number = preg_replace($pattern, '', $number);

After this operation, we might need to cast it back to the number for type safety cases.
Also we can use str_replace

Limiting number of decimals after decimal point
This also can be achieved in different ways:
1. Using function:

number_format($number, 2); //takes the two digits next to decimal point

2. Using regex:

preg_match('/(d+(.?d{0,2})?)/', $number, $matches); // here matches[0] would contain the required value

See how you would solve these known algorithm problems

Java solution for checking anagram strings – tell if phrases are anagrams

Get maximum occurring character

Find K Complementary numbers from array Java implementation

Finding missing numbers from billion sequential number list file

testing k complementary pairs algorithm with junit

Find the first occurence of number in the sorted array

binary tree problems with solution

Implementing tokenizer and adding tokens to the linked list

find longest word in the sentence

Check if two strings are anagrams or not

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*