Home > Mobile >  Float number saves as integer in MySQL using TypeORM
Float number saves as integer in MySQL using TypeORM

Time:01-05

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?

CodePudding user response:

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.

  • Related