javascript数字精度而不转换为String [英] javascript number precision without converting to String

查看:76
本文介绍了javascript数字精度而不转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发REST API并返回JSON。其中一个字段称为submittingPercent,我需要它是一个数字,但必须精确到小数点后两位

I am developing a REST API and returning JSON. One of the fields is called submissionPercent and I need it to be a number but with exactly 2 decimal places


  • 如果submissionPercent为20,我需要返回20.00。

  • 如果submittingPercent为20.238,我需要返回20.24。

但是submissionPercent应该是不是数字的字符串。
如果我使用 toFixed toPrecision ,那么我得到的是一个字符串。

But submissionPercent should be a number not a String. If I use toFixed or toPrecision, then what I get is a String.

如果可能,如何实现?

推荐答案

var n = 20.238;

Math.round(n * 100) / 100
// => 20.24

或更笼统地说:

function roundWithPrecision(num, precision) {
  var multiplier = Math.pow(10, precision);
  return Math.round( num * multiplier ) / multiplier;
}

roundWithPrecision(20.238, 2)
// => 20.24

roundWithPrecision(20.238, 1)
// => 20.2

正如其他人指出的那样, 20 20.00 完全相同,因此,如果您希望用户看到小数点后的两位数字(即使它们为零),则必须使用字符串格式像 toFixed 这样的功能。

As others have pointed out, 20 and 20.00 are exactly the same, so if you want the user to see two digits after the decimal point even if they're zero, you'll have to use a string formatting function like toFixed.

对于JSON API,由消费者决定如何存储解码时的值。即使您要输出表示 {val:20.00} 的JSON,消费者也将使用它选择的宽度存储它。它可能以32位浮点数或64位浮点数结尾。它可能以字符串结尾。它可能最终出现在 VARCHAR(6)列的MySQL数据库中。您无法控制使用者如何处理您的数据,这是设计使然。

In the case of a JSON API, it's up to the consumer to decide how to store the value upon decoding it. Even if you were to output JSON that said { val: 20.00 } a consumer will store it with whatever width it chooses. It might end up in a 32-bit float or a 64-bit float. It might end up in a string. It might end up in a MySQL database in a VARCHAR(6) column. You can't control how the consumer treats your data, and this is by design.

输出 {val:20.00}没有优势。 {值:20} {值:20.00000} {val:2000e-2} 。如果希望API使用者假定两位数的精度,则应将该信息放入API文档中。我鼓励这样做,因为它将帮助其他开发人员在实现API客户端时做出决定。

There is no advantage to outputting { val: 20.00 } over { val: 20 } or { val: 20.00000 } or { val: 2000e-2 }. If you want the API consumer to assume two digits of precision, you should put that information in your API documentation. I would encourage this, as it will help other developers make decisions when implementing API clients.

这篇关于javascript数字精度而不转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆