- number_format
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- User Contributed Notes 9 notes
- PHP — Convert integer variable value to decimal
- PHP — Convert integer variable value to decimal
- Formatting Decimal Places in PHP
- How to extract integer and decimal numbers in PHP string correctly?
- How to transform last two numbers to decimal (int to float) in php?
number_format
Formats a number with grouped thousands and optionally decimal digits using the rounding half up rule.
Parameters
The number being formatted.
Sets the number of decimal digits. If 0 , the decimal_separator is omitted from the return value.
Sets the separator for the decimal point.
Sets the thousands separator.
Return Values
A formatted version of num .
Changelog
Version | Description |
---|---|
8.0.0 | Prior to this version, number_format() accepted one, two, or four parameters (but not three). |
7.2.0 | number_format() was changed to not being able to return -0 , previously -0 could be returned for cases like where num would be -0.01 . |
Examples
Example #1 number_format() Example
For instance, French notation usually use two decimals, comma (‘,’) as decimal separator, and space (‘ ‘) as thousand separator. The following example demonstrates various ways to format a number:
// english notation (default)
$english_format_number = number_format ( $number );
// 1,235
// French notation
$nombre_format_francais = number_format ( $number , 2 , ‘,’ , ‘ ‘ );
// 1 234,56
// english notation without thousands separator
$english_format_number = number_format ( $number , 2 , ‘.’ , » );
// 1234.57
See Also
- money_format() — Formats a number as a currency string
- sprintf() — Return a formatted string
- printf() — Output a formatted string
- sscanf() — Parses input from a string according to a format
User Contributed Notes 9 notes
It’s not explicitly documented; number_format also rounds:
$numbers = array( 0.001 , 0.002 , 0.003 , 0.004 , 0.005 , 0.006 , 0.007 , 0.008 , 0.009 );
foreach ( $numbers as $number )
print $number . «->» . number_format ( $number , 2 , ‘.’ , ‘,’ ). «
» ;
?>
0.001->0.00
0.002->0.00
0.003->0.00
0.004->0.00
0.005->0.01
0.006->0.01
0.007->0.01
0.008->0.01
0.009->0.01
Note: use NumberFormatter to convert in human-readable format instead user function from comments:
echo NumberFormatter :: create ( ‘en’ , NumberFormatter :: SPELLOUT )-> format ( 12309 ); // twelve thousand three hundred nine
echo NumberFormatter :: create ( ‘ru’ , NumberFormatter :: SPELLOUT )-> format ( 12307.5 ); // двенадцать тысяч триста семь целых пять десятых
?>
If you want to display a number ending with ,- (like 200,-) when there are no decimal characters and display the decimals when there are decimal characters i use:
function DisplayDouble($value)
list($whole, $decimals) = split (‘[.,]’, $value, 2);
if (intval($decimals) > 0)
return number_format($value,2,».»,»,»);
else
return number_format($value,0,».»,»,») .»,-«;
>
Outputs a human readable number.
# Output easy-to-read numbers
# by james at bandit.co.nz
function bd_nice_number ( $n ) // first strip any formatting;
$n = ( 0 + str_replace ( «,» , «» , $n ));
// is this a number?
if(! is_numeric ( $n )) return false ;
// now filter it;
if( $n > 1000000000000 ) return round (( $n / 1000000000000 ), 1 ). ‘ trillion’ ;
else if( $n > 1000000000 ) return round (( $n / 1000000000 ), 1 ). ‘ billion’ ;
else if( $n > 1000000 ) return round (( $n / 1000000 ), 1 ). ‘ million’ ;
else if( $n > 1000 ) return round (( $n / 1000 ), 1 ). ‘ thousand’ ;
return number_format ( $n );
>
?>
Outputs:
247,704,360 -> 247.7 million
866,965,260,000 -> 867 billion
For Zero fill — just use the sprintf() function
$pr_id = 1;
$pr_id = sprintf(«%03d», $pr_id);
echo $pr_id;
$pr_id = 10;
$pr_id = sprintf(«%03d», $pr_id);
echo $pr_id;
You can change %03d to %04d, etc.
I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.
I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.
function number_format_unlimited_precision ( $number , $decimal = ‘.’ )
$broken_number = explode ( $decimal , $number );
return number_format ( $broken_number [ 0 ]). $decimal . $broken_number [ 1 ];
>
?>
formatting numbers may be more easy if u use number_format function.
I also wrote this :
function something($number)
$locale = localeconv();
return number_format($number,
$locale[‘frac_digits’],
$locale[‘decimal_point’],
$locale[‘thousands_sep’]);
>
My simpler solution to the problem of the decimal number in this function being longer than the specified number of decimals.
Standard result for number_format() is..
number_format(5.00098, 2) = 5.00
My function will return the result = 5.001
// ** Warning: Does not work with scientific notation. Conversion to a real number is required. **
echo auto_decimal_format ( 5.0005620 ); // print 5.0006
echo auto_decimal_format ( 5.0009820 ); // print 5.001
echo auto_decimal_format ( 5.00098 , 8 ); // print 5.00098000
echo auto_decimal_format ( 1.0295691366783E-5 , 2 ); // print 0.00
function auto_decimal_format ( $n , $def = 2 ) $a = explode ( «.» , $n );
if ( count ( $a )> 1 ) $b = str_split ( $a [ 1 ]);
$pos = 1 ;
foreach ( $b as $value ) if ( $value != 0 && $pos >= $def ) $c = number_format ( $n , $pos );
$c_len = strlen ( substr ( strrchr ( $c , «.» ), 1 ));
if ( $c_len > $def ) < return rtrim ( $c , 0 ); >
return $c ; // or break
>
$pos ++;
>
>
return number_format ( $n , $def );
>
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):
function fnumber_format ( $number , $decimals = » , $sep1 = » , $sep2 = » )
if (( $number * pow ( 10 , $decimals + 1 ) % 10 ) == 5 ) //if next not significant digit is 5
$number -= pow ( 10 , -( $decimals + 1 ));
return number_format ( $number , $decimals , $sep1 , $sep2 );
$t = 7.15 ;
echo $t . » | » . number_format ( $t , 1 , ‘.’ , ‘,’ ) . » | » . fnumber_format ( $t , 1 , ‘.’ , ‘,’ ) . «\n\n» ;
//result is: 7.15 | 7.2 | 7.1
$t = 7.3215 ;
echo $t . » | » . number_format ( $t , 3 , ‘.’ , ‘,’ ) . » | » . fnumber_format ( $t , 3 , ‘.’ , ‘,’ ) . «\n\n» ;
//result is: 7.3215 | 7.322 | 7.321
> ?>
have fun!
PHP — Convert integer variable value to decimal
Solution 3: Probably not the most elegant way to do it but you could use two preg_replace functions based on your first REGEX and remove the decimals without any numbers wrapped around them like so : Live example here : https://3v4l.org/9aUCt Question: I need transform to , to or any number with 3 digits or more to record in db like a decimal. Output: Solution 2: You can also do it like this: Output: Solution 3: How about , is this what you are looking for? http://php.net/manual/en/function.number-format.php Question: I have a string in PHP where I want to extract only integer and decimal numbers, this is an example: In this case I try to get numbers using this line:
PHP — Convert integer variable value to decimal
I have a variable fl_duration which takes integer value 1,2,3. I am looking to create a new variable ‘decimal’ which will return the value as a decimal number i.e. 0.1 , 0.2, 0.3.
$decimal = get_field('fl_duration');
Any ideas would be much appreciated.
PHP will convert it to an float itself so you can just do it by basic math.
You can also do it like this:
$int = 1; $dec = (float) "0.$int"; // or $dec = (double) "0.$int"; var_dump($dec);
How about number_format() , is this what you are looking for? http://php.net/manual/en/function.number-format.php
$decimal = number_format( 1, 2); //will give you string(4) "1.00"
Show a number to two decimal places, Show a number to two decimal places What’s the correct way to round a PHP string to two decimal places? $number = «520»; // It’s a string from a database $
Formatting Decimal Places in PHP
Your browser can’t play this video. Learn more. Switch camera.
Duration: 3:52
How to extract integer and decimal numbers in PHP string correctly?
I have a string in PHP where I want to extract only integer and decimal numbers, this is an example:
In this case I try to get numbers using this line:
$numbers = preg_replace('/[^0-9\.,]/', ' ', $string);
But the problem is the result is:
25 957 1859 . , 25.957 1.859 . , . . . 1859 , 25 957 1 343 392 . 94 . 50,95 .
And I want to get this result:
25 957 1859 25.957 1.859 1859 25 957 1 343 392 94 50,95
You’re using a . for thousands and a , for decimals, and it looks like your text is intended for humans so there will always be a number immediately before a . and , .
So what you want is 1 or more numbers, followed by 0 or more thousand-groups (a . followed by 3 more numbers), optionally followed by exactly one , and one or more numbers.
One or more numbers: 4+ 0 or more thousand-groups: (\.8)* Optionally a `,` and one or more numbers: (,9+)?
$string = 'María vive en un pueblo de 25 957 habitantes y cobra 1859 euros al mes. OJO: no sé si os habéis fijado, pero los números del último ejemplo no llevan un punto o una coma separando los millares (25.957 o 1.859). Sé que resulta extraño, pero la nueva normativa de la R.A.E. dice que los números de cuatro cifras NO llevarán separación (1859) y los números de cinco cifras o más NO llevarán ni puntos ni comas, sino una separación (25 957 o 1 343 392). El 94% de los niños ha traído los deberes hechos. He pagado $50,95 dólares.'; $matches = []; preg_match_all('/6+(\.7)*(,4+)?/', $string, $matches); print_r($matches[0]); /* Array ( [0] => 25 [1] => 957 [2] => 1859 [3] => 25.957 [4] => 1.859 [5] => 1859 [6] => 25 [7] => 957 [8] => 1 [9] => 343 [10] => 392 [11] => 94 [12] => 50,95 ) */
Use this regular expression:
NOTE
This exp will match 25 957 like 2 matches (for the space between numbers).
Probably not the most elegant way to do it but you could use two preg_replace functions based on your first REGEX and remove the decimals without any numbers wrapped around them like so :
$numbers = preg_replace('/[^0-9\.,]+/', ' ', $string); $decimals = preg_replace('/([^0-9][\.,])/', '', $numbers); var_dump($decimals); // string(56) " 25 957 1859 25.957 1.859 1859 25 957 1 343 392 94 50,95"
Live example here : https://3v4l.org/9aUCt
Cast int to float, two decimal values in PHP [duplicate], round((float)$i, 2) Should do the trick. The round function is built in and rounds a given float to the number of decimal places specified
How to transform last two numbers to decimal (int to float) in php?
I need transform 100 to 1.00 , 345 to 3.45 or any number with 3 digits or more to record in db like a decimal.
Don’t need add .00 , just transform last two numbers in decimal.
I try number_format($num, 2) but is wrong.
It seems, that you want to divide your numbers to 100 , so using number_format() with the appropriate $decimal_separator and $thousands_separator is an option:
Since you are converting from an integer to a float, you can achieve this simply by dividing the number by 100.
$input = 100; $value = floatval($input) / 100; $value = number_format($value, 2); echo $value;
You may then use number_format (as you were using before) to force two decimal places after any evenly divided float numbers (such as 100).
Demo: PHP Sandbox Example
Why a decimal value from MySQL is converted into/shown as integer?, Problem is that whenever I use << $quotation->cost >> to display the information, all the decimals are printed as integers like ( 25 , 4 , 10 ).<>