PHP float does not round up the method of intercepting floating-point string

Source: Internet
Author: User
There are several ways to intercept floating-point types in PHP. Need friends can come to the reference, I hope to help you

There are several ways to intercept floating-point types in PHP:

1, float round (float $val [, int $precision]) Returns the result of rounding Val based on the specified precision precision (number of digits after decimal decimal point). Precision can also be negative or 0 (the default value).

echo round (4.3)//4

2 . String sprintf (String $format [, Mixed $args [, mixed $ ...]) returns the formatted data strings

$a = 12.338938438; Echo sprintf ("%.5f", $a)//Result: 12.33894  $a =12.3312356, echo sprintf ("%.5f", $a),//12.33124 echo sprintf ("%f", $a);// 331236  default 6 digits after decimal point

3, string Number_format (float $number, int $decimals, String $dec _point, string $thousands _sep)

$number = 1234.5678; $english _format_number = Number_format ($number, 2, '. ', '); echo  $english _format_number;//1234.57

All of these are automatically rounded, sometimes demand does not need to be rounded up, how to do, did not think of a good way, who know can tell a sound.

I wrote a trouble-point function and recorded it.

function Getfloatvalue ($f, $len) {   $tmpInt =intval ($f);   $tmpDecimal = $f-$tmpInt;   $str = "$tmpDecimal";   $subStr =strstr ($str, '. ');   if (strlen ($SUBSTR) < $len + 1)  {   $repeatCount = $len +1-strlen ($subStr);   $str = $str. "". Str_repeat ("0", $repeatCount);  }   return    $tmpInt. "". substr ($str, 1,1+ $len); } Echo Getfloatvalue (12.99,4)//12.9900 echo getfloatvalue (12.9232555553239,4)//12.9232

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.