You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Postman中验证API响应的货币字段为两位小数数字?

Postman验证JSON响应中的合法货币金额(两位小数数字)

要验证JSON响应中的字段为保留两位小数的数字类型,可以在现有数字类型验证的基础上,增加小数位数的校验,以下是两种可行方案:

方案一:通过数学计算验证

利用乘法取整再还原的方式,判断原数字是否仅保留两位小数:

pm.test("验证ltd是保留两位小数的数字", function () {
    var jsonData = pm.response.json();
    const targetAmount = jsonData.testingexample[0].ltd;
    // 第一步:验证字段为数字类型
    pm.expect(targetAmount).to.be.a("Number");
    // 第二步:验证仅保留两位小数
    pm.expect(targetAmount).to.equal(Math.round(targetAmount * 100) / 100);
});

原理:将数字乘以100后取整,再除以100,若结果与原数字相等,说明原数字最多只有两位小数(如12.34 → 1234 → 12.34;12.345 → 1235 → 12.35,与原数不等)。

方案二:转字符串后用正则匹配

将数字转为字符串,通过正则匹配确保格式符合两位小数的要求:

pm.test("验证ltd是合法货币金额", function () {
    var jsonData = pm.response.json();
    const targetAmount = jsonData.testingexample[0].ltd;
    // 验证字段为数字类型
    pm.expect(targetAmount).to.be.a("Number");
    // 匹配两位小数格式,支持整数的话可将正则改为 /^\d+(\.\d{2})?$/
    pm.expect(targetAmount.toString()).to.match(/^\d+\.\d{2}$/);
});

如果业务允许货币金额为整数(如100等同于100.00),或者支持负数金额,可调整正则:

  • 支持整数:/^\d+(\.\d{2})?$/
  • 支持负数:/^-?\d+\.\d{2}$/
  • 同时支持整数和负数:/^-?\d+(\.\d{2})?$/

内容的提问来源于stack exchange,提问作者Abby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:32:47