PHP
PHP Numeric and String Conversion with Decimal Precision
단모모
2024. 3. 15. 10:25
728x90
php 코드의 숫자형, 문자형 변환 과 round 함수에 대해 알아 본다.
Numeric to String Conversion: 숫자형을 문자형으로
$numeric_value = 123;
$string_value = (string)$numeric_value; // Typecasting
// or
$string_value = $numeric_value . ""; // Concatenation
String to Numeric Conversion: 문자형을 숫자형으로
$string_value = "123";
$integer_value = intval($string_value); // For integers
$float_value = floatval($string_value); // For floats
// or
$integer_value = (int)$string_value; // Typecasting for integers
$float_value = (float)$string_value; // Typecasting for floats
Defining Decimal Precision: 소수잠 자리수
$float_number = 123.4567;
$formatted_number = number_format($float_number, 2); // Formats to 2 decimal places
// Output: 123.46
Rounding Modes: 올림, 반올림
- PHP_ROUND_HALF_UP: Round halves up
- PHP_ROUND_HALF_DOWN: Round halves down
- PHP_ROUND_HALF_EVEN: Round halves to even numbers
- PHP_ROUND_HALF_ODD: Round halves to odd numbers
$number = 10.5;
$rounded_up = round($number, 0, PHP_ROUND_HALF_UP);
$rounded_down = round($number, 0, PHP_ROUND_HALF_DOWN);
echo $rounded_up; // Output: 11
echo $rounded_down; // Output: 10
728x90