Aditi Jalaj
Aditi Jalaj

Reputation: 11

How to add 4 decimal places as precision while defining Schema in mongoose

I am designing a wallet rest api where I am taking wallet balance as request body. I can enter balance as 10.123456 but i want to keep the decimal precision upto 4 places. that is my response gets saved with 10.1234. What can my approach be?

Upvotes: 1

Views: 188

Answers (1)

Fabian Strathaus
Fabian Strathaus

Reputation: 3570

You can use the following code:

const input = 10.123456;
const rounded = Math.floor(input * 10000) / 10000;

console.log(rounded);

You can, of course, add this code to your schema directly like:

myValue: {
    type: Number,
    set: v => Math.floor(v * 10000) / 10000
  }

Upvotes: 1

Related Questions