JS Number函数将此字符串转换为“ 1,255,558.3652”,出现“ Nan”

时间:2018-08-11 07:34:42

标签: javascript jquery

我使用import 'dart:async'; import 'dart:io'; String _host = InternetAddress.loopbackIPv4.host; Future main() async { var server = await HttpServer.bind(_host, 3333); await for (var req in server) { ContentType contentType = req.headers.contentType; HttpResponse response = req.response; if (req.method == 'POST' && contentType?.mimeType == 'multipart/form-data' /*1*/) { try { // DECODE Multipart request here and write to file, but not sure how req.response ..statusCode = HttpStatus.ok ..write('Wrote data'); } catch (e) { response ..statusCode = HttpStatus.internalServerError ..write("Exception during file I/O: $e."); } } else { response ..statusCode = HttpStatus.methodNotAllowed ..write("Unsupported request: ${req.method}."); } response.close(); } } 将此字符串转换为数字,但控制台中的结果告诉我“ Nan”。

在我的html代码中,我使用:

@Entity
@Table(name = "isin")
public class IsIn {

    @EmbeddedId
    private UserGroupId id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn("userId")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn("groupId")
    private Group group;

使用时格式化输入:

Number("1,255,558.3652")

要获取值,它说“ Nan”,那我该怎么办?

2 个答案:

答案 0 :(得分:3)

Number无法识别其中包含逗号的数字字符串。首先删除所有逗号:

console.log(Number(
  "1,255,558.3652".replace(/,/g, '')
));

答案 1 :(得分:0)

您的input元素允许使用诸如123....123之类的值。如果您这样做:

Number(
  "123....123".replace(/,/g, '')
)

它仍然会给您NaN。为了防止这种情况发生,并且建议使用浮点值,请使用parseFloat()而不是Number()。使用它会阻止NaN的输出:

您会得到正确的 1245634 (但不是NaN)

parseFloat(
  "12,456,34...123".replace(/,/g, '')
);

console.log(parseFloat(
  "12,456,34...123".replace(/,/g, '')
));

您得到 1234564.123

parseFloat(
  "1,234,564.123".replace(/,/g, '')
);

console.log(parseFloat(
  "1,234,564.123".replace(/,/g, '')
));