Javascript 为什么我的 toFixed() 函数不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4937251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:51:39  来源:igfitidea点击:

Why is my toFixed() function not working?

javascriptjquerynumber-formatting

提问by Ben

Here's the relevant code. I've confirmed with the alert that the correct number is saved, it's just not being changed to 2 decimal places.

这是相关的代码。我已经通过警报确认保存了正确的数字,只是没有更改为小数点后两位。

if ($(this).attr('name') == 'time') {
    var value = $(this).val();
    parseFloat(value).toFixed(2);
    alert(value);
    editEntry.time = value;
}

回答by Marc B

You're not assigning the parsed float back to your value var:

您没有将解析的浮点数分配回您的值 var:

value = parseFloat(value).toFixed(2);

should fix things up.

应该解决问题。

回答by Pulath Yaseen

I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".

我多次尝试函数 toFixed(2) 。每次控制台显示“toFixed() 不是函数”。

but how I resolved is By using Math.round()

但我的解决方法是使用 Math.round()

eg:

例如:

if ($(this).attr('name') == 'time') {
    var value = parseFloat($(this).val());
    value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3
    alert(value);
}

this thing surely works for me and it might help you guys too...

这东西肯定对我有用,它也可能对你们有帮助......

回答by KARTHIKEYAN.A

Your conversion data is response[25] and follow the below steps.

您的转化数据是 response[25] 并按照以下步骤操作。

var i = parseFloat(response[25]).toFixed(2)
console.log(i)//-6527.34

回答by Vlad

Example simple (worked):

示例简单(有效):

var a=Number.parseFloat($("#budget_project").val()); // from input field
var b=Number.parseFloat(html); // from ajax
var c=a-b;
$("#result").html(c.toFixed(2)); // put to id='result' (div or others)

回答by Mauricio Parizotto

document.getElementById("EDTVALOR").addEventListener("change", function() {
  this.value = this.value.replace(",", ".");
  this.value = parseFloat(this.value).toFixed(2);
  if (this.value < 0) {
    this.value = 0;
  }
  this.value = this.value.replace(".", ",");
  this.value = this.value.replace("NaN", "0");
});