javascript format price

房东的猫 提交于 2019-12-07 11:45:10

问题


I wish to format a variable to a price format where if it is for example $90 then leave out the decimal which it already does anyway. But if the value is $44.5 then I want to format it as $44.50. I can do it in php not javascript.

PHP example:

number_format($price, !($price == (int)$price) * 2);

The code I want to format:

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

回答1:


var price = 44.5;    
var dplaces = price == parseInt(price, 10) ? 0 : 2;
price = '$' + price.toFixed(dplaces);



回答2:


PHPJS has that code for you: http://phpjs.org/functions/money_format:876

Also provided by @Daok How can I format numbers as money in JavaScript?




回答3:


Try this

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;
    }
}


来源:https://stackoverflow.com/questions/7772699/javascript-format-price

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