0

I am using the row_to_json function to convert a table row to a json object. There are a few columns in the table that are of type numeric which contain float values.

When row_to_json returns the json, values like 9.98 becomes 9.98000000000000043 or 6.30 becomes 6.29999999999999982 in these numeric columns.

Is there a way to impose precision at the json creation function? There are no other data issues in the table which are affecting other modules. Changing the column type to numeric(12,2) etc. is not possible since the table has over 2 billion rows(the table would be locked for 30+hours) and would affect other production modules.

--update--

I should have made the question a little bit clearer with the use case.

row_to_json is used in a trigger to audit updates in the DB. The json result is stored in another table and this same audit function is used for multiple tables(100+) where there may be other tables with this same issue.

One solution would be to handle it at the application level when retrieving the jsons from the audit table, but I would like to see if there is a function that can handle it in the DB itself.

  • Using a normal "select row_to_json(table) from table" gives the right value without any loss of precision. But in the trigger(a BEFORE UPDATE trigger), using "row_to_json(NEW)" leads to a loss in precision. – Min2j Feb 3 '18 at 17:30
0

You can round the values:

select row_to_json(t)
from (
  select id, 
         round(value_1, 2) as value_1, 
         round(value_2, 2) as value_2
  from test
) t;

If you need that more often and don't want to type it all the time, create a view that returns the rounded values.

  • Thank you for the response @a_horse_with_no_name . This would work for normal retrieval queries which require JSONs. But for triggers with different tables and columns(column names in each of the tables) with this problem of precision, this issue would not work. I have updated the question to make it clearer. – Min2j Jan 29 '18 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.