PHP Floating-point comparison size method _php Tips

Source: Internet
Author: User
Tags php error string methods

The example in this article tells you how to compare the PHP floating-point size. Share to everyone for your reference, specific as follows:

<?php
/**
 * Floating-point numbers are generally not used to compare size, but we can use a flexible way to
 use var_dump output floating-point is not see the effect, you can use Serialize view
 * 1.round 2. Floating-point conversions to Strings
 *
 * Converting to String methods:
 * Convert to String by preceding (string) or by using the Strval () function
 * In an expression that requires a string, the string automatically transitions, such as using the function echo () or print (), or when a variable is compared to a string, the transformation
 * True will change to 1, and false to an empty string
 *
/$a = 13.2;
$b =;
$c = $a/$b;
The actual value is this d:0.54999999999999993338661852249060757458209991455078125;
Echo Serialize ($c). ' <br/> '//
echo $c. ' <br/> '//output will show 0.55 the actual value is smaller than his
//So direct and 0.55 comparison size is not tenable
if ($c = = 0.55) {
  echo ' nothing ';
}
$c = Round ($c, 2);
Use round to process
if ($c = = 0.55) {
  echo ' OK ';
}
echo "<br/>";
Force to a string
//$c = (string) $c;
$c = Strval ($c);
if ("$c" = = 0.55) {
  echo ' OK ';
}
? >

The results of the operation are as follows:

d:0.54999999999999993338661852249060757458209991455078125;
0.55
OK
OK

For more information about PHP interested readers can view the site topics: "PHP Operations and Operator Usage Summary", "PHP basic Grammar Introductory Course", "PHP error and Exception handling method summary" and "PHP common functions and Skills summary"

I hope this article will help you with the PHP program design.

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.