24

I have a number in JavaScript that I'd like to convert to a money format:

556633 -> £5566.33

How do I do this in JavaScript?

0

5 Answers 5

56

Try this:

var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"
Sign up to request clarification or add additional context in comments.

4 Comments

+1 for ensuring 2 decimal places (plus toFixed also handles rounding)
+1, to improve, you may ensure that it returns a number with a parseFloat rather than a string
Be aware of the fact that this outputs a string.
how to get the typeof to be number but still retain the trailing zero; Example parseFloat(3.6 + 4.4).toFixed(1) output to be number => 8.0 than string "8.0"
17

This works:

var currencyString = "£" + (amount/100).toFixed(2);

3 Comments

This returns a string... :(
yes - this answer is over 14 years old. There was pretty much no numerical currency handling options back then. No ECMA internationalisation API, npm packages weren't a thing (by staggering coincidence, this answer was published on the day the first version of npm was released). Back then, if you wanted a number formatted as a currency, you did it all by yourself, by formatting the number and pre-pending the currency symbol to create a string.
sorry man, I didn't notice the age of the answer. Cheers
6

Try

"£"+556633/100

3 Comments

I'd say "£" + (556633 / 100) to be sure.
Works for this exact case, but how about if the number 556633.9 was fed in. Then it gives too many decimal places.
You are right Rob Levine, if OP want 2 decimal places, need to do .toFixed(2), but there is answers for that already, I wouldn't update my answer.
4

This script making only integer to decimal. Seperate the thousands

onclick='alert(MakeDecimal(123456789));' 


function MakeDecimal(Number) {
        Number = Number + "" // Convert Number to string if not
        Number = Number.split('').reverse().join(''); //Reverse string
        var Result = "";
        for (i = 0; i <= Number.length; i += 3) {
            Result = Result + Number.substring(i, i + 3) + ".";
        }
        Result = Result.split('').reverse().join(''); //Reverse again
        if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
        if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
        return Result;

    }

Comments

-1

Using template literals you can achieve this:

const num = 556633;
const formattedNum = `${num/100}.00`;
console.log(formattedNum); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.