Using number_format to add thousand separator

自闭症网瘾萝莉.ら 提交于 2021-01-03 03:10:57

问题


I'm trying to quite simply take the number that is inside the variable $output and turn it into a number with a thousand separator. The number it current outputs is 49995 but I want it to appear as 49,995.

Having some trouble. Help?

function twitter_followers($user = 'mytwitterusername'){
    // Build Twitter api url
    $apiurl = "http://api.twitter.com/1/users/show.json?screen_name={$user}";

    //cache request
    $transient_key = $user . "_twitter_followers";

    // If cached (transient) data are used, output an HTML
    // comment indicating such
    $cached = get_transient( $transient_key );

    if ( false !== $cached ) {
        return $cached;
    }

    // Request the API data, using the constructed URL
    $remote = wp_remote_get( esc_url( $apiurl ) );

    // If the API data request results in an error, return
    // an appropriate comment
    if ( is_wp_error( $remote ) ) {
        return '<p>Twitter unaviable</p>';
    }

    // If the API returns a server error in response, output
    // an error message indicating the server response.
    if ( '200' != $remote['response']['code'] ) {
        return '<p>Twitter responded with an HTTP status code of '. esc_html( $remote['response']['code']) . '</p>';
    }

    // If the API returns a valid response, the data will be
    // json-encoded; so decode it.
    $data = json_decode( $remote['body'] );

    $output = $data->followers_count;
    $followers = number_format($output,2,'.',',');

    set_transient( $transient_key, $output, 600 );

    return $followers;
}

回答1:


I've tested the following code and it works:

$output = 49995;
$followers = number_format( $output , 0 , '.' , ',' );
echo $followers;

Not sure why your code is not working. Also make sure to set the second parameter to 0, unless you want decimal points. Perhaps the value of $output initially is a string and you need to cast it as an integer before putting it through number_format()?




回答2:


Your number_format seems to be right. Try an

$output = intval($data->followers_count);

before calling it, maybe there is an issue after decoding the value.



来源:https://stackoverflow.com/questions/11459998/using-number-format-to-add-thousand-separator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!