user1091856
user1091856

Reputation: 3158

Javascript: Function that converts integer into string (money representation)?

In my database, I store money values without any points or commas. So I need a Javascript function that converts it into money string.

Example: Convert 500 (five dollars) into 5.00 , 100 into 1.00, 550 into 5.50 etc

Can anybody post a function like that?

Upvotes: 2

Views: 1302

Answers (4)

KooiInc
KooiInc

Reputation: 122906

You can use something like:

function toAmount(amount){
  amount = Number(amount);
  if (isNaN(amount)){
    throw 'invalid: can\'t convert input';
  }
  return (amount/100).toFixed(2);
}
//usage
toAmount(500);    //=> 5.00
toAmount(520873); //=> 5208.73
toAmount('500');  //=> 5.00

Or use that function as an extension to Number

Number.prototype.toAmount = function toAmount(amount){
  return (this/100).toFixed(2);
};
//usage:
(500).toAmount();    //= 5.00
(520873).toAmount(); //=> 5208.73

Upvotes: 2

Tim
Tim

Reputation: 7780

Simply divide the number by 100 then to make sure it always has decimals use the Javascript function toFixed(2).

So it looks like:

function ConvertCentsToDollars(cents) {
    var dollars = cents / 100;
    var dollars = dollars.toFixed(2);
    return dollars;
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 707258

You can use various string operations (I chose to use slice()) to extract the last two characters, insert a period in between and construct the final string. The advantage of doing it this way is you avoid some of the inaccuracies that floating point math can sometimes have:

var num = 500;
var numStr = num.toString();
var formattedStr = numStr.slice(0,-2) + "." + numStr.slice(-2);

If you just wanted to use floating point math, you could do:

var num = 500;
var formattedStr = (num / 100).toFixed(2).toString();

The operative part of this last one is the toFixed() method that rounds and zero pads a decimal number to an exact number of digits (which is exactly what you want for money). You can read about toFixed() in this MDN reference.

You can see both of them working here: http://jsfiddle.net/jfriend00/pApVR/

Upvotes: 0

Arbejdsglæde
Arbejdsglæde

Reputation: 14088

if it easy just divide your value on 100; after this you can add ".00" value if unnecessary

​var valdb = 500;
var format = (valdb/100)+".00";
alert(format);

Upvotes: 0

Related Questions