number_format()函数期望参数1是浮点数,但提供了字符串。

huangapple go评论59阅读模式
英文:

php number format error - number_format() expects parameter 1 to be float, string given

问题

请问有人可以帮我解决这个代码问题吗?

>Number_format()期望参数1为浮点数,但传递了字符串

我的代码:

public static function format_inr($value, $decimals = 0) {
    setlocale(LC_MONETARY, 'en_IN');
    if (function_exists('money_format')) {
        return money_format('%!i.' . $decimals . 'i', round($value));
    } else {
        return number_format($value, 2);
    }
}
英文:

Can you please someone help me with this code I got

>Number_format() expects parameter 1 to be float, string given

my Code:

public static function format_inr($value, $decimals = 0) {
    setlocale(LC_MONETARY, 'en_IN');
    if (function_exists('money_format')) {
        return money_format('%!i.' . $decimals . 'i', round($value));
    } else {
        return number_format($value, 2);
    }
}

答案1

得分: 0

你可以通过将变量$value的内容强制转换为浮点数来解决此问题。因此,如果$value的类型不是浮点数,你可以强制PHP将内容解释为浮点数。

public static function format_inr($value, $decimals = 0) {
    // ...
        return number_format((float) $value, 2);
    // ..
}

作为一个附注:我认为最好在函数中使用类型提示。这样,在函数调用中,你期望$value是一个浮点数,因此每个方法调用者都被指示使用浮点数调用方法,而不是字符串或整数。因此,你不需要再次强制转换变量,因为你确保得到的是一个浮点数。方法调用者必须负责进行必要的强制转换。

public static function format_inr(float $value, $decimals = 0) {
    // ...
        return number_format($value, 2);
    // ..
}
英文:

You can fix this with casting the content of the variable $value into float. So if the type of $value is not float, you can force PHP to interpret the content as float.

public static function format_inr($value, $decimals = 0) {
    // ...
        return number_format((float) $value, 2);
    // ..
}

as a side node: I guess it's better to use type hints for the function. so you expect $value as float in the function call, so every method caller was instructed to call the method with a float, not a string or an integer. So you don't need to cast the variable again, because you are sure you getting a float. the method caller has to be take care of casting, if needed.

public static function format_inr(float $value, $decimals = 0) {
    // ...
        return number_format($value, 2);
    // ..
}

huangapple
  • 本文由 发表于 2023年6月16日 13:30:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定