简体   繁体   中英

How do I convert an integer to decimal in JavaScript?

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?

Try this:

var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"

这有效:

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

试试

"£"+556633/100

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;

    }

Using template literals you can achieve this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM