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

如何在Sequelize查询中限制Double类型字段的小数位数至2或3位?

解决方案:限制Sequelize查询中Double类型字段的小数位数

针对你的场景,要把double precision类型的savings_percent字段限制为2或3位小数,这里有三种实用的方法,你可以根据需求灵活选择:

方法1:数据库层面直接处理(推荐)

利用PostgreSQL的ROUND函数(正好匹配你的字段类型),在查询阶段就让数据库返回处理后的数值,这种方式高效且能减少前端的处理工作量。

修改你的控制器查询代码,通过Sequelize的fn和col工具调用数据库函数:

const { fn, col } = require('sequelize'); // 记得引入这两个工具函数

const chw = await Prjt_source_percent_each.findOne({
  where: { project_id, commodity: 'CHW', phase: 'predicted' },
  attributes: [
    // 保留你需要的其他字段
    'project_id',
    'commodity',
    'phase',
    // 处理savings_percent:第二个参数是小数位数,2位或3位按需修改
    [fn('ROUND', col('savings_percent'), 2), 'savings_percent']
  ]
});

这样查询返回的chw.savings_percent就是已经格式化好的数值。

方法2:查询后在JavaScript中处理

如果不想改动查询逻辑,也可以在拿到数据库返回结果后,用JS原生方法处理小数位数:

用toFixed方法(注意返回值是字符串,需转数字)

const chw = await Prjt_source_percent_each.findOne({ where: { project_id, commodity: 'CHW', phase: 'predicted' } });
// 保留2位小数,转成数字类型
chw.savings_percent = Number(chw.savings_percent.toFixed(2));
// 要3位小数的话改成toFixed(3)

用Math.round手动计算

const chw = await Prjt_source_percent_each.findOne({ where: { project_id, commodity: 'CHW', phase: 'predicted' } });
// 保留2位小数
chw.savings_percent = Math.round(chw.savings_percent * 100) / 100;
// 保留3位小数则改为 *1000 /1000

这种方式适合需要临时调整小数位数,或者仅在特定场景处理的情况,注意浮点数精度问题(一般展示场景影响不大)。

方法3:在模型中添加虚拟字段(一劳永逸)

如果每次查询这个模型都需要格式化 savings_percent,可以在模型里定义一个虚拟字段,自动完成处理:

修改你的模型代码,新增一个虚拟字段(推荐不修改原字段,避免混淆):

'use strict';
const { Model, DataTypes } = require('sequelize');
module.exports = (sequelize) => {
  class Prjt_source_percent_each extends Model {
    static associate(models) {
      // define association here
    }
  };
  Prjt_source_percent_each.init({
    project_id: DataTypes.STRING,
    phase: DataTypes.STRING,
    commodity: DataTypes.STRING,
    comm_type: DataTypes.STRING,
    source_energy_baseline: DataTypes.REAL,
    source_energy_savings: DataTypes.REAL,
    savings_percent: DataTypes.DOUBLE,
    // 添加虚拟字段,自动格式化savings_percent为2位小数
    formatted_savings_percent: {
      type: DataTypes.VIRTUAL,
      get() {
        return Math.round(this.savings_percent * 100) / 100;
        // 需要3位小数的话改成 *1000 /1000
      }
    }
  }, {
    sequelize,
    modelName: 'Prjt_source_percent_each',
    tableName: 'prjt_source_percent_each',
    timestamps: false
  });
  Prjt_source_percent_each.removeAttribute('id');
  return Prjt_source_percent_each;
};

之后查询时,直接调用chw.formatted_savings_percent就能拿到格式化后的数值了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:54:05