Below i have a use case, where a number is stored in db as decimal(18, 2). When trying to read the data, the numbers with .00 are converted to integer.
Using .toFixed(2) changes the format from number to string. // as expected.
How can i retain the format.
Input
const x1 = 4000.00;
const x2 = 4000.01;
const y1 = parseFloat((x1).toFixed(2)); // actual: 4000 expected: 4000.00
const y2 = parseFloat((x2).toFixed(2)); // actual: 4000.01 expected: 4000.01
// const y1 = parseFloat((x1).toFixed(2)).toFixed(2); //datatype: actual: string, expected: number
// const y2 = parseFloat((x2).toFixed(2)).toFixed(2); //datatype: actual: string, expected: number
console.log(typeof(y1), y1);
console.log(typeof(y2), y2);
decimal(18,2) is a fixed-precision number format, here meaning "18 decimal digit, with 2 of them to the right of the decimal point". Typically stored as either packed decimal or an integer. with precision and scale maintained by the programming language.
Javascript numbers are not like that. They are IEEE 754 double-precision binary floating point numbers: they have a floating decimal (binary) point, and trade precision for range.
You need to read What Every Programmer Should Know About Floating-Point Arithmetic, or Why don’t my numbers add up?.