我有下面的代码。我想让它这样,如果price_result等于一个整数,比如10,然后我想加两位小数点后。所以10就是10.00。 如果等于10.6,就是10.60。不知道该怎么做。

price_result = parseFloat(test_var.split('$')[1].slice(0,-1));

当前回答

要返回一个数字,添加另一层圆括号。保持清洁。

var twoPlacedFloat = parseFloat((10.02745).toFixed(2));

其他回答

当你使用toFixed时,它总是以字符串的形式返回值。这有时会使代码复杂化。为了避免这种情况,您可以为Number创建一个替代方法。

Number.prototype.round = function(p) {
  p = p || 10;
  return parseFloat( this.toFixed(p) );
};

和使用:

var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143

或者仅仅是:

(22/7).round(3); // 3.143

试试这个(参见代码中的注释):

function fixInteger(el) {
    // this is element's value selector, you should use your own
    value = $(el).val();
    if (value == '') {
        value = 0;
    }
    newValue = parseInt(value);
    // if new value is Nan (when input is a string with no integers in it)
    if (isNaN(newValue)) {
        value = 0;
        newValue = parseInt(value);
    }
    // apply new value to element
    $(el).val(newValue);
}

function fixPrice(el) {
    // this is element's value selector, you should use your own
    value = $(el).val();
    if (value == '') {
        value = 0;
    }
    newValue = parseFloat(value.replace(',', '.')).toFixed(2);
    // if new value is Nan (when input is a string with no integers in it)
    if (isNaN(newValue)) {
        value = 0;
        newValue = parseFloat(value).toFixed(2);
    }
    // apply new value to element
    $(el).val(newValue);
}

您可以将价格存储为字符串

你可以使用 (字符串)

用于计算。

例子

Number("34.50") == 34.5

also

Number("35.65") == 35.65

如果你对数字函数感到舒服,你可以使用它。

下面是对我有效的解决方案

parseFloat(value)

我已经为我的案子试过了,它会工作得很好。

var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);

样例输出:

9.007