Home >Backend Development >PHP Problem >How to convert to 6 decimal places in php
Conversion method: 1. Use "round(value, 6)" to round the value into 6 decimal places; 2. Use "sprintf("%.6f", value)" to format the value into 6 decimal places; 3. Use "number_format(value, 6)" to convert the thousand-digit group formatted value into 6 decimal places.
The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.
1. Use the round() function.
round() function rounds floating point numbers.
Syntax
round(number,precision,mode);
number Required. Specifies the value to be rounded.
precision Optional. Specifies the number of digits after the decimal point. The default is 0, which can also be negative.
mode Optional. Specifies constants representing rounding modes:
2. Use the sprintf() function.
The sprintf() function writes a formatted string into a variable.
arg1, arg2, parameters will be inserted into the main string at the percent sign (%) symbol. This function is executed step by step. At the first % sign, insert arg1, at the second % sign, arg2, and so on.
Syntax
sprintf(format,arg1,arg2,arg++)
format Required. Specifies a string and how to format variables within it.
3. Use the number_format() function.
number_format() function formats a number by grouping by thousands.
This function supports one, two or four parameters (not three).
Syntax
number_format(number,decimals,decimalpoint,separator)
The example is as follows
<?php $num = 10.456715616; //第一种:利用round()对浮点数进行四舍五入 echo round($num,6)."<br>"; //第二种:利用sprintf格式化字符串 $format_num = sprintf("%.6f",$num); echo $format_num."<br>"; //第三种:利用千位分组来格式化数字的函数number_format() echo number_format($num, 6); ?>
Output result:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert to 6 decimal places in php. For more information, please follow other related articles on the PHP Chinese website!