Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript format 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);
like image 727
Keith Power Avatar asked Oct 14 '11 19:10

Keith Power


People also ask

How do I format a value in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.

How do you format currency value?

On the Home tab, click the Dialog Box Launcher next to Number. Tip: You can also press Ctrl+1 to open the Format Cells dialog box. In the Format Cells dialog box, in the Category list, click Currency or Accounting. In the Symbol box, click the currency symbol that you want.

What is js currency?

currency. js is a lightweight ~1kb javascript library for working with currency values. It was built to work around floating point issues in javascript.

Is there .format in JavaScript?

In javascript, there is no built-in string formatting function.


3 Answers

var price = 44.5;    
var dplaces = price == parseInt(price, 10) ? 0 : 2;
price = '$' + price.toFixed(dplaces);
like image 66
James Avatar answered Oct 08 '22 15:10

James


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?

like image 24
AlienWebguy Avatar answered Oct 08 '22 15:10

AlienWebguy


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;
    }
}
like image 33
mandelbaum Avatar answered Oct 08 '22 17:10

mandelbaum