Problems with rounding numbers

Source: Internet
Author: User
such as $a=1.2;
echo $a; I'm going to let it show up here as 1.5.

$a = 1.6;
echo $a; I'm going to let it show up here as 2.

That is, when the value after the decimal point of $ A is less than 5 o'clock (excluding 0), it is displayed as 5来, and the value after the decimal point is greater than 5 o'clock as normal rounding


Reply to discussion (solution)

$n = 1.2;//$n = 1.6; $t = explode ('. ', "$n"); $n = $t [1]{0} < 5? $t [0] +. 5:round ($n); Echo $n;

function test ($val) {$x =explode ('. ', sprintf ("%.1f", $val)); $a = $x [0]; $d = $x [1];if ($d >0 && $d <5) {$r = $a + 0.5;} else{$r =round ($val);} return $r;} echo Test (1);//1echo test (1.11);//1.5echo test (1.5);//2echo test (1.6);//2

function fn ($num) {
return Ceil ($num * 2)/2;
}

$n = 1.2;//$n = 1.6; $t = explode ('. ', "$n"); $n = $t [1]{0} < 5? $t [0] +. 5:round ($n); Echo $n;



If the $n=1.5//is still showing 1.5

function test ($val) {$x =explode ('. ', sprintf ("%.1f", $val)); $a = $x [0]; $d = $x [1];if ($d >0 && $d <5) {$r = $a + 0.5;} else{$r =round ($val);} return $r;} echo Test (1);//1echo test (1.11);//1.5echo test (1.5);//2echo test (1.6);//2



In this way,

needs to be clear.

for ($i =1; $i <2; $i +=0.1)  printf ("%.1f:%s\n", $i, Ceil ($i * 2)/2);
1.0:11.1:1.51.2:1.51.3:1.51.4:1.51.5:21.6:21.7:21.8:21.9:2

function fn ($num) {
return Ceil ($num * 2)/2;
}



+1

$arr = Array (1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1), foreach ($arr as $v) {echo $v. '. Fn ($v). '
';} function fn ($num) {return ($ret =round ($num, 0)) >= $num? $ret: $ret +0.5;}


1-1
1.1-1.5
1.2-1.5
1.3-1.5
1.4-1.5
1.5-2
1.6-2
1.7-2
1.8-2
1.9-2
2-2
2.1-2.5

needs to be clear.

for ($i =1; $i <2; $i +=0.1)  printf ("%.1f:%s\n", $i, Ceil ($i * 2)/2);
1.0:11.1:1.51.2:1.51.3:1.51.4:1.51.5:21.6:21.7:21.8:21.9:2


CLASSIC,!!!!!.
  • 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.