developer tip

숫자의 정수 및 소수 부분을 얻는 방법?

optionbox 2020. 9. 13. 10:24
반응형

숫자의 정수 및 소수 부분을 얻는 방법?


1.25라고 가정하면이 숫자의 "1"과. "25"부분을 어떻게 얻습니까?

소수점이 .0, .25, .5 또는 .75인지 확인해야합니다.


$n = 1.25;
$whole = floor($n);      // 1
$fraction = $n - $whole; // .25

그런 다음 1/4, 1/2, 3/4 등과 비교하십시오.


음수의 경우 다음을 사용하십시오.

function NumberBreakdown($number, $returnUnsigned = false)
{
  $negative = 1;
  if ($number < 0)
  {
    $negative = -1;
    $number *= -1;
  }

  if ($returnUnsigned){
    return array(
      floor($number),
      ($number - floor($number))
    );
  }

  return array(
    floor($number) * $negative,
    ($number - floor($number)) * $negative
  );
}

$returnUnsigned하기에서 정지 -1.25를 위해서는 -1-0.25


이 코드는이를 분할합니다.

list($whole, $decimal) = explode('.', $your_number);

여기서 $ whole은 정수이고 $ decimal은 소수점 뒤에 자리를 갖습니다.


그냥 다르게 :)

list($whole, $decimal) = sscanf(1.5, '%d.%d');

CodePad .

추가 이점으로 양쪽이 숫자로 구성된 경우에만 분할됩니다.


floor () 메서드는 음수에 대해 작동하지 않습니다. 이것은 매번 작동합니다.

$num = 5.7;
$whole = (int) $num;  // 5
$frac  = $num - (int) $num;  // .7

... 음수에도 작동합니다 (동일한 코드, 다른 숫자) :

$num = -5.7;
$whole = (int) $num;  // -5
$frac  = $num - (int) $num;  // -.7

int로 캐스팅하고 빼기

$integer = (int)$your_number;
$decimal = $your_number - $integer;

또는 비교를 위해 소수를 얻으려면

$decimal = $your_number - (int)$your_number

짧은 방법 (floor 및 fmod 사용)

$var = "1.25";
$whole = floor($var);     // 1
$decimal = fmod($var, 1); //0.25

그런 다음 $ decimal을 0, .25, .5 또는 .75와 비교하십시오.


사용할 수있는 fmod 함수도 있습니다. fmod ($ my_var, 1)는 동일한 결과를 반환하지만 때로는 작은 라운드 오류가 발생합니다.


PHP 5.4 이상

$n = 12.343;
intval($n); // 12
explode('.', number_format($n, 1))[1]; // 3
explode('.', number_format($n, 2))[1]; // 34
explode('.', number_format($n, 3))[1]; // 343
explode('.', number_format($n, 4))[1]; // 3430

이것이 내가 사용하는 방법입니다.

$float = 4.3;    

$dec = ltrim(($float - floor($float)),"0."); // result .3

Brad Christie의 방법은 본질적으로 정확하지만 더 간결하게 작성할 수 있습니다.

function extractFraction ($value) 
{
    $fraction   = $value - floor ($value);
    if ($value < 0)
    {
        $fraction *= -1;
    }

    return $fraction;
}

이것은 그의 방법과 동일하지만 결과적으로 더 짧고 이해하기가 더 쉽습니다.


$x = 1.24

$result = $x - floor($x);

echo $result; // .24

여분의 부동 소수점을 방지하기 위해 (즉, 50.85-50은 0.850000000852를 제공합니다), 제 경우에는 돈 센트에 소수점 2 자리 만 필요합니다.

$n = 50.85;
$whole = intval($n);
$fraction = $n * 100 % 100;

실제로 달러 금액과 소수점 이하 금액을 구분하는 방법을 찾기가 어려웠습니다. 대부분 알아 낸 것 같아요. 문제가 생기면 공유하려고 생각 했어요

그래서 기본적으로...

if price is 1234.44... whole would be 1234 and decimal would be 44 or

if price is 1234.01... whole would be 1234 and decimal would be 01 or

if price is 1234.10... whole would be 1234 and decimal would be 10

and so forth

$price = 1234.44;

$whole = intval($price); // 1234
$decimal1 = $price - $whole; // 0.44000000000005 uh oh! that's why it needs... (see next line)
$decimal2 = round($decimal1, 2); // 0.44 this will round off the excess numbers
$decimal = substr($decimal2, 2); // 44 this removed the first 2 characters

if ($decimal == 1) { $decimal = 10; } // Michel's warning is correct...
if ($decimal == 2) { $decimal = 20; } // if the price is 1234.10... the decimal will be 1...
if ($decimal == 3) { $decimal = 30; } // so make sure to add these rules too
if ($decimal == 4) { $decimal = 40; }
if ($decimal == 5) { $decimal = 50; }
if ($decimal == 6) { $decimal = 60; }
if ($decimal == 7) { $decimal = 70; }
if ($decimal == 8) { $decimal = 80; }
if ($decimal == 9) { $decimal = 90; }

echo 'The dollar amount is ' . $whole . ' and the decimal amount is ' . $decimal;

If you can count on it always having 2 decimal places, you can just use a string operation:

$decimal = 1.25;
substr($decimal,-2);  // returns "25" as a string

No idea of performance but for my simple case this was much better...


Not seen a simple modulus here...

$number         = 1.25;
$wholeAsFloat   = floor($number);   // 1.00
$wholeAsInt     = intval($number);  // 1
$decimal        = $number % 1;      // 0.25

In this case getting both $wholeAs? and $decimal don't depend on the other. (You can just take 1 of the 3 outputs independently.) I've shown $wholeAsFloat and $wholeAsInt because floor() returns a float type number even though the number it returns will always be whole. (This is important if you're passing the result into a type-hinted function parameter.)

I wanted this to split a floating point number of hours/minutes, e.g. 96.25, into hours and minutes separately for a DateInterval instance as 96 hours 15 minutes. I did this as follows:

$interval = new \DateInterval(sprintf("PT%dH%dM", intval($hours), (($hours % 1) * 60)));

I didn't care about seconds in my case.


val = -3.1234

fraction = abs(val - as.integer(val) ) 

참고URL : https://stackoverflow.com/questions/6619377/how-to-get-whole-and-decimal-part-of-a-number

반응형