开发者

How to format a dollar? [duplicate]

开发者 https://www.devze.com 2023-02-18 14:07 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: 开发者_如何学CHow can I format numbers as money in JavaScript?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

开发者_如何学CHow can I format numbers as money in JavaScript?

I am doing a divide and multiply to figure out the value of a field and the value looks like this

$32560.000000000004.00

I am setting the value like this

sq_footage = $("#sq_footage").val();
sq_footage_total = (((sq_footage / 36) * factor) * average )* 30;
if(factor != ""){
    $("#new_calc").val("$" + sq_footage_total + ".00");
}

Is there a way to format it like

$32,560.00


I know this has been solved before, but here's my solution just for fun:

function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    return ["$", p[0].split("").reverse().reduce(function(acc, num, i) {
        return num + (i && !(i % 3) ? "," : "") + acc;
    }, "."), p[1]].join("");
}

And some tests:

formatDollar(45664544.23423) // "$45,664,544.23"
formatDollar(45) // "$45.00"
formatDollar(123) // "$123.00"
formatDollar(7824) // "$7,824.00"
formatDollar(1) // "$1.00"
formatDollar(939,009) // ?

function formatDollar(num) {
      var p = num.toFixed(2).split(".");
      return ["$", p[0].split("").reverse().reduce(function(acc, num, i) {
        return num + (i && !(i % 3) ? "," : "") + acc;
      }, "."), p[1]].join("");
    }


    const tests = [
      {
        input: 45664544.23423,
        expected: "$45,664,544.23"
      },
      {
        input: 45,
        expected: "$45.00"
      },
      {
        input: 123,
        expected: "$123.00"
      },
      {
        input: 7824,
        expected: "$7,824.00"
      },
      {
        input: 1,
        expected: "$1.00"
      },
      {
        input: -939009,
        expected: "-$939,009.00"
      }
    ]

    tests.forEach(test => {
      const { input, expected } = test
      const actual = formatDollar(input)
      if (expected !== actual) {
        console.log(`Failed: ${input}. Expected ${expected}; actual: ${actual}`)
      } else {
        console.log(`Passed: ${input}`)
      }
    })


Your tag indicates that you are using jquery - so you might use the jQuery Format Currency Plugin

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号