开发者

Fix Javascript Value to 0 decimals

I have this script which is working in formatting my currency but now its not fixing my value to 0 decimal places, Im new to javascript so could anybody explain where and hwo I'd do this? Thanks

function FormatNumberBy3(num, decpoint, sep) {
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ",";
  }
  if (arguments.length == 1) {
    sep = ",";
    decpoint = ".";
  }
  // need a strin开发者_高级运维g for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x;
}


I may be misunderstanding your question, but it sounds like you want Math.floor()

http://www.javascripter.net/faq/mathfunc.htm


You can round numbers mathematically, which is much, much faster and much, much, much simpler. There are literally hundreds of examples of this algorithm all over this site alone.

function round(number, places)
{
    var multiplicator = Math.pow(10, places);
    return Math.round(number * multiplicator) / multiplicator;
}

alert(round(123.456, 0)); // alerts "123"

This function lets you round to an arbitrary decimal place. If you want to round to the nearest integer, you may simply use Math.round(x).

Math.round rounds a decimal number to the nearest integer. Assuming you want to keep 3 decimal places, all you have to do is multiply the decimal number by 1000 (which is 10 power 3), round to the nearest integer, then divide by 1000. This is what this snippet does.


Your function appears to work for me... I assume the result of passing "1000" as an argument should be "1,000"? I'm not sure I understand what you mean by "fixing [your] value to 0 decimal places".

Here's a function I wrote to format numbers (like your above function does) for an API once:

function num_format(str) {
    if (typeof str !== 'string' || /[^\d,\.e+-]/.test(str)) {
        if (typeof str === 'number') {
            str = str.toString();
        } else {
            throw new TypeError("Argument is not a string with a number in it");
        }
    }
    var reg = /(\d+)(\d{3})/;
    str = str.split(".");
    while (reg.test(str[0])) {
        str[0] = str[0].replace(reg, "$1,$2");
    }
    return str.join(".");
}

Remove the error checking code and it becomes quite a short little function (five lines). Pass it any number and it will format it correctly, although I didn't allow the option of specifying the separators.

As for rounding numbers to arbitrary decimal places, I suggest seeing zneak's answer above. Then would simply do:

num_format(round("100000.12341234", 2));

Which would give a result of "100,000.12".


This function should be capable of all various scenarios:

function formatNumber(num, precision, sep, thousand, addTrailing0) {
    if (isNaN(num))
        return "";
    if (isNaN(precision))
        precision = 2;
    if (typeof addTrailing0 == "undefined")
        addTrailing0 = true;

    var factor = Math.pow(10, precision);
    num = String(Math.round(num * factor) / factor);

    if (addTrailing0 && precision > 0) {
        if (num.indexOf(".") < 0)
            num += ".";
        for (var length = num.substr(num.indexOf(".")+1).length; length < precision; ++length)
            num += "0";
    }

    var parts = num.split(".");
    parts[0] = parts[0].split("").reverse().join("").replace(/(\d{3})(?=\d)/g, "$1" + (thousand || ",")).split("").reverse().join("");

    num = parts[0] + (parts.length > 1 ? (sep || ".") + parts[1] : "");

    //debug:
    document.write(num + "<br />");

    return num;
}

Examples:

formatNumber(32432342342.3574, 0);             // 32,432,342,342
formatNumber(32432342342.3574, 2);             // 32,432,342,342.36
formatNumber(1342.525423, 4, ".", ",");        //          1,342.5254
formatNumber(1342.525423, 2, ",", ".");        //          1.342,53
formatNumber(1342.525423);                     //          1,342.53
formatNumber(1342.525423, 0);                  //          1,343
formatNumber(342.525423, 8);                   //            342.52542300
formatNumber(42.525423, 8, null, null, false); //             42.525423
formatNumber(2.5, 3, ",", ".");                //              2,500

Working Live Demo at http://jsfiddle.net/roberkules/xCqqh/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜