最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript format price - Stack Overflow

programmeradmin4浏览0评论

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

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);
Share Improve this question asked Oct 14, 2011 at 19:36 Keith PowerKeith Power 14.1k23 gold badges70 silver badges140 bronze badges
Add a comment  | 

3 Answers 3

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

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?

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;
    }
}
发布评论

评论列表(0)

  1. 暂无评论