Summary of methods for intercepting float strings in php rounding

Source: Internet
Author: User
There are roughly the following methods to intercept floating point in php. For more information, see php. FloatThere are roughly the following methods:

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

Echo round (4.3) // 4

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

$ A = 12.338938438; echo sprintf ("%. 5f ", $ a) // Result: 12.33894 $ a = 12.3312356; echo sprintf (" %. 5f ", $ a); // 12.33124 echo sprintf (" % f ", $ a); // 331236 the default value is 6 digits after the 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 the above are automatically rounded down. sometimes the demand does not need to be rounded down. what should I do? I didn't think of a good solution. who knows I can tell you.

I wrote a troublesome 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

For more information about the methods of intercepting float strings in php float, refer to the Chinese PHP website!

Related articles:

Rounding php Data processing

Full function rounding in php

Three methods to implement rounding in PHP

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.