UFO ET IT

PHP 번호 : 필요한 경우에만 소수점 표시

ufoet 2020. 12. 31. 22:42
반응형

PHP 번호 : 필요한 경우에만 소수점 표시


10 진수로 숫자 형식을 자동으로 지정하는 기능이 있는지 알고 싶습니다.

<?php
    // $sql_result["col_number"] == 1,455.75
    number_format ($sql_result["col_number"], 2, ".", "");
    // will return 1455.75

    // $sql_result["col_number"] == 1,455.00
    number_format ($sql_result["col_number"], 2, ".", "");
    // could I get 1455 instead of 1455.00?
?>

그래서 내 대답은 DB에 DECIMAL 데이터 형식이 반올림 인 경우에만 소수를 제거하는 방법이 있습니까?

아니면 내가 그런 짓을한다고 소리 치나요?

<?php
    // $sql_result["col_number"] == 1,455.00
    str_replace(".00", "", (string)number_format ($sql_result["col_number"], 2, ".", ""));
    // will return 1455
?>

나는 실제로 당신의 해결 방법이 어떤 것만큼이나 좋다고 생각합니다. 간단하고 명확하며 여기서 성능에 대해 이야기 할 필요가 없습니다.


floatval 또는 단순히 부동으로 캐스팅

php > echo floatval(7.00);
7
php > echo floatval(2.30);
2.3
php > echo floatval(1.25);
1.25
php > echo floatval(1.125);
1.125

php > echo (float) 7.00;
7
php > echo (float) 2.30;
2.3
php > echo (float) 1.25;
1.25
php > echo (float) 1.125;
1.125

Emil이 당신의 것이 좋다고 말했듯이. 그러나 0예를 들어 제거하려는 경우 7.50제안이 있습니다 rtrim().

<?php
    // if $sql_result["col_number"] == 1,455.50
    rtrim(rtrim(number_format($sql_result["col_number"], 2, ".", ""), '0'), '.');
    // will return 1455.5
?>

필요한 경우 느슨한 소수없이 값을 정리하는 더 좋은 방법으로 PHP의 소수에서 쓸모없는 0 자릿수 제거 기사를 추가합니다 .


또한 rtrim ()을 사용하여 초과 0을 제거 할 수 있습니다. 소수점 하나만 유지하고 초과 0은 유지하지 않으려는 경우입니다. (예를 들어 4.50은 4.5가됩니다.) 또한 소수 자릿수를 2에서 다른 숫자로 변경할 수 있습니다.

rtrim(rtrim((string)number_format($value, 2, ".", ""),"0"),".");

// 4.00 -> 4
// 4.50 -> 4.5
// 4.54000000 -> 4.54 (if you're doing more decimal places)

사실 저는 이런 종류의 검색을 한 사람을 위해이 작업을 수행 할 수있는 가장 깨끗한 방법은 다음과 같이하는 것입니다.

( number_format ($sql_result["col_number"], 2) * 100 ) / 100;

미국 통화를 타겟팅하는 경우이 방법을 사용합니다.

function moneyform($number, $symbol = true) {
    return str_replace(".00", "", money_format(($symbol? '%.2n' : "%!n"), $number));
}

moneyform(1300999);
-->$1,300,999

moneyform(2500.99);
-->$2,500.99

moneyform(2500.99, false);
-->2,500.99

Warren.S 답변이 나를 도왔습니다. number_format 함수가 필요하지 않았기 때문에이 작업을 수행했습니다.

$value=$value-0;

그러나 OP의 경우 쉼표를 제거하려면 number_format이 필요합니다. 그래서 이것은 그를 위해 일할 것입니다

$value=number_format ($sql_result["col_number"], 2, ".", "")-0;

유연한 솔루션을 찾을 수 없었기 때문에 최상의 결과를 얻기 위해 간단한 함수를 작성했습니다.

function getValueFormattedWithMinimalDecimals($value, $max_decimals = 2, $dec_point = ',', $thousands_sep = '') {
    $bestNumberOfDecimals = -1;
    $decimal = 0;
    while ($decimal <= $max_decimals) {
        $bestNumberOfDecimals = $decimal;
        $valueDecimals = number_format($value, $decimal);
        if (floatval($value) == $valueDecimals) {
            break;
        }
        $decimal++;
    }
    if($bestNumberOfDecimals > 0 && number_format($value, $bestNumberOfDecimals) == number_format($value, 0)) {
        $bestNumberOfDecimals = 0;
    }

    return number_format($value, $bestNumberOfDecimals, $dec_point, $thousands_sep);
}

나는 다음과 같은 일을 한 혐의를 받았습니다.

 floatval($foo) == intval($foo) ? number_format($foo) : number_format($foo,2);

Mine since most quantity or pieces do not require decimal, this function will only show decimal when needed.

str_replace(".00", "", number_format($this->pieces, 2));

What about

number_format($value,2) - 0;

ReferenceURL : https://stackoverflow.com/questions/4113200/php-number-decimal-point-visible-only-if-needed

반응형