如何在 php 中将 NAN 转换为 0
How to convert NAN to 0 in php
我正在计算数据库 table 中值的百分比,但是,当没有值时,函数 returns NAN,我希望函数为 return 0相反,我使用的函数是:
function calculate_percentages($atts){
global $wpdb;
$postid = get_the_ID();
$myrate_name = "sql_table_name";
$total_count = $wpdb->get_var( "SELECT SUM(rates) FROM $myrate_name WHERE post_id=$postid");
$top = $wpdb->get_var( "SELECT SUM(rates) FROM $myrate_name WHERE rating = 5 AND post_id=$postid");
$top_avarage = round($top/$total_count*100);
return $top_avarage;
您有一个 php 函数可以使用 is_nan
$top_average = !is_nan($top/$total_count*100) ? round($top/$total_count*100) : 0;
你得到 NAN
因为 $total_count
是 0
或计算结果为 0
的东西,你不能除以 0
。所以检查它是否是 0
,如果是,则将结果设置为 0
,如果不是,则进行计算:
$top_average = $total_count != 0 ? round($top/$total_count*100) : 0;
我正在计算数据库 table 中值的百分比,但是,当没有值时,函数 returns NAN,我希望函数为 return 0相反,我使用的函数是:
function calculate_percentages($atts){
global $wpdb;
$postid = get_the_ID();
$myrate_name = "sql_table_name";
$total_count = $wpdb->get_var( "SELECT SUM(rates) FROM $myrate_name WHERE post_id=$postid");
$top = $wpdb->get_var( "SELECT SUM(rates) FROM $myrate_name WHERE rating = 5 AND post_id=$postid");
$top_avarage = round($top/$total_count*100);
return $top_avarage;
您有一个 php 函数可以使用 is_nan
$top_average = !is_nan($top/$total_count*100) ? round($top/$total_count*100) : 0;
你得到 NAN
因为 $total_count
是 0
或计算结果为 0
的东西,你不能除以 0
。所以检查它是否是 0
,如果是,则将结果设置为 0
,如果不是,则进行计算:
$top_average = $total_count != 0 ? round($top/$total_count*100) : 0;