Number() not converting floating points from db correct

59 views Asked by At

I am using sinclair/typebox for TypeScript project, here is my schema:

export const ItemValue = Type.Object({
  itemBalance: Type.Number()
}) 

export type ItemValueType = Static<typeof ItemValue>;

how I am reading this data from oracle db:

const result = await connection.execut<ItemValueType>(query, {
{
  outFormat: OUT_FORMAT_OBJECT
}
})

The issue is that there is a value in oracle 15.79 which is being returned as 15.790000000000001

any ideas how to fix this issue?

3

There are 3 answers

0
Toseef Zafar On BEST ANSWER

I ended up using TO_CHAR function in my query like so:

SELECT TO_CHAR(my_column, 'FM99.99') as myColumn from myTable

This resolved my issue.

0
JGFMK On
let n = 15.790000000000001;
let m = n.toFixed(2);
document.write(m)
0
TheHungryCub On

The issue you’re facing with the precision of floating-point numbers is common when dealing with numerical data.

One way to address this is by rounding the number to a specific decimal precision. You can use the toFixed() method to round the number to a fixed number of decimal places.

You can modify your code to round the itemBalance value like:

const result = await connection.execut<ItemValueType>(query, {
  {
    outFormat: OUT_FORMAT_OBJECT
  }
});


if (result.itemBalance !== undefined) {
  result.itemBalance = Number(result.itemBalance.toFixed(2)); // Rounding to 2 decimal places
}

This will round the itemBalance value to two decimal places before further processing, ensuring consistent precision.