Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript格式价格_Javascript_Format - Fatal编程技术网

javascript格式价格

javascript格式价格,javascript,format,Javascript,Format,我希望将一个变量格式化为价格格式,例如,如果它是$90,则省略小数点,反正它已经这样做了。但是如果值是$44.5,那么我想将其格式化为$44.50。我可以用php而不是javascript来完成 PHP示例: number_format($price, !($price == (int)$price) * 2); 我要格式化的代码: $(showdiv+' .calc_price span').html(sum_price); PHPJS为您提供了以下代码: 也是由@Daok提供的,试试这个

我希望将一个变量格式化为价格格式,例如,如果它是$90,则省略小数点,反正它已经这样做了。但是如果值是$44.5,那么我想将其格式化为$44.50。我可以用php而不是javascript来完成

PHP示例:

number_format($price, !($price == (int)$price) * 2);
我要格式化的代码:

$(showdiv+' .calc_price span').html(sum_price);

PHPJS为您提供了以下代码:

也是由@Daok提供的,试试这个

function priceFormatter(price)
{
    //Checks if price is an integer
    if(price == parseInt(price))
    {    
        return "$" + price;
    }

    //Checks if price has only 1 decimal
    else if(Math.round(price*10)/10 == price)
    {
        return "$" + price + "0";
    }

    //Covers other cases
    else
    {
        return "$" + Math.round(price*100)/100;
    }
}
function priceFormatter(price)
{
    //Checks if price is an integer
    if(price == parseInt(price))
    {    
        return "$" + price;
    }

    //Checks if price has only 1 decimal
    else if(Math.round(price*10)/10 == price)
    {
        return "$" + price + "0";
    }

    //Covers other cases
    else
    {
        return "$" + Math.round(price*100)/100;
    }
}