개발 꿀팁/PHP

[PHP] Decimal point conversion, truncation, rounding, and rounding of numeric type variables

Jammie 2018. 1. 19. 12:23
반응형

When processing data of a numeric type, conversion can be done in various ways when it is necessary to convert the number of decimal places. The most commonly used methods are rounding, rounding, and discarding.


floor (value to convert) // decimal point discarded

ceil (value to convert) // Decimal point

round (value to convert) // round to decimal


You can use it simply as above. Then look at the example below.


* See an example of decimal handling in php

If the variable $ testnum exists as below, it can be converted as follows.


<? php

$testnum = 12.345;


echo floor ($testnum);

// Outputs 12. Decimal point discarded


echo ceil ($testnum)

// Outputs 13. Decimal Point Rounded


echo round ($testnum)

// Output 12. Rounding applied to output

?>



* How to output only the desired number of decimal places

You can use the round () function to return only the desired number of rounds. Look at the example below.


<? php

$testnum = 12.3456;


echo round ($testnum, 2);

// Outputs 12.35. Round off to two decimal places


echo round ($testnun, 3);

// output 12.345

?>

반응형