在MySQL中使用TypeORM将浮点数保存为整数。

huangapple go评论140阅读模式
英文:

Float number saves as integer in MySQL using TypeORM

问题

我在我的Nest.js后端应用中使用TypeORM。当我尝试将实体保存到数据库时:

  1. await this.dayRepository.save({
  2. price: item.price,
  3. ...其他列
  4. });

而我的价格是浮点数,但在数据库中以整数保存 - 总是截断(3.99变成3,5.56变成5等)。我甚至尝试了这样:

  1. await this.dayRepository.save({
  2. price: 3.99,
  3. ...其他列
  4. });

它还将价格列保存在数据库中为3。我尝试将数据库中的价格列声明为浮点数和双精度 - 都不起作用。我做错了什么?或者可能是数据库的问题?

英文:

I'm using TypeORM for my Nest.js backend app. When I try to save entity in database:

  1. await this.dayRepository.save({
  2. price: item.price,
  3. ... other columns
  4. });

And my price is float, that float saves in database as integer - always truncated (3.99 round to 3, 5.56 round to 5 etc.). I even try this:

  1. await this.dayRepository.save({
  2. price: 3.99,
  3. ... other columns
  4. });

And it also saves price column in database as 3. I tried to declare my price column in database as float and double - none of that worked. What I'm doing wrong? Or it could be some issue with database?

答案1

得分: 4

根据TypeORM文档,您可以检查mysql的列类型。

因此,您可以在实体中声明值,类似于以下方式:

  1. @Column('decimal', { precision: 6, scale: 2 })
  2. price: number

其中,precisionscale是您自行选择的数字,但我认为您想要将scale设置为2。

您可以查看此文档

precision是用于十进制(精确数值)列的精度(仅适用于十进制列),它是存储值的最大数字位数。

scale是用于十进制(精确数值)列的刻度(仅适用于十进制列),表示小数点右侧的数字位数,不得大于精度。

通过这种实体配置,您可以存储带有小数的值。

英文:

According to TypeORM docs you can check the column types for mysql.

So you can declare the value something like this in your entity:

  1. @Column('decimal', { precision: 6, scale: 2 })
  2. price: number

Where precision and scale are number at your election, but I think you want scale as 2.

You can check this docs

> The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values.

> The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision.

With this entity configuration you can store values with decimals.

huangapple
  • 本文由 发表于 2023年1月5日 03:33:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75010411.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定