英文:
Float number saves as integer in MySQL using TypeORM
问题
我在我的Nest.js后端应用中使用TypeORM。当我尝试将实体保存到数据库时:
await this.dayRepository.save({
price: item.price,
...其他列
});
而我的价格是浮点数,但在数据库中以整数保存 - 总是截断(3.99变成3,5.56变成5等)。我甚至尝试了这样:
await this.dayRepository.save({
price: 3.99,
...其他列
});
它还将价格列保存在数据库中为3。我尝试将数据库中的价格列声明为浮点数和双精度 - 都不起作用。我做错了什么?或者可能是数据库的问题?
英文:
I'm using TypeORM for my Nest.js backend app. When I try to save entity in database:
await this.dayRepository.save({
price: item.price,
... other columns
});
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:
await this.dayRepository.save({
price: 3.99,
... other columns
});
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
的列类型。
因此,您可以在实体中声明值,类似于以下方式:
@Column('decimal', { precision: 6, scale: 2 })
price: number
其中,precision
和scale
是您自行选择的数字,但我认为您想要将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:
@Column('decimal', { precision: 6, scale: 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论