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

String Ordered Permutation Algorithm Problem

Implement Queue Using two Stacks – JavaScript algorithm

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

Finding missing numbers from billion sequential number list file

Kadane’s algorithm in C – Dynamic Programming

find longest word in the sentence

Implementing tokenizer and adding tokens to the linked list

Flatten nested javascript array

binary tree problems with solution

Check if there are three numbers a, b, c giving a total T from array A

Leave a Reply

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

*
*