【问题标题】:Using toFixed to get a decimal number for a number field使用 toFixed 获取数字字段的十进制数
【发布时间】:2018-04-04 08:16:22
【问题描述】:

我有这个字段

<input type="number" name="amount" step="0.01" ng-model="amount" />

$scope.amount 是一个变量,其中的值是一个字符串,所以我这样做:

$scope.amount = parseInt($scope.amount).toFixed(2);

这确实返回了比方说0.00 的值,但它在一个字符串中,但它不会填充该字段,因为它只是一个数字字段并且toFixed(); 正在返回一个字符串,即使我仍然解析它。

有什么办法解决这个问题?

【问题讨论】:

  • 您想将变量存储为数字,不是吗?
  • type="number" 不支持浮点数。你需要改成type="text"
  • <input type="number"> 没有格式属性,因此它总是会删除不必要的小数位。 (好吧,如果您键入数字,它将保留零,但如果您通过代码设置数字则不会)

标签: javascript angularjs numbers decimal


【解决方案1】:

使用 parseFloat $scope.amount = parseFloat(parseInt($scope.amount).toFixed(2));

toFixed() 将数字转换为字符串 在这里查看https://www.w3schools.com/jsref/jsref_tofixed.asp

【讨论】:

  • 这只是返回值 0。
  • 好的,所以这是特定于“0.00”的,parseFloat 会给你零。在这种情况下,你需要更改你以将输入类型更改为文本并使用 onChange 方法通过代码处理验证。
猜你喜欢
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 2022-01-06
  • 2015-02-04
  • 2014-04-30
  • 2014-05-02
  • 2014-12-20
  • 2015-08-08
相关资源
最近更新 更多