Question

I would like to learn best practices for formatting numerical data resulting from an HSQLDB select query for human readable output. The goal is to be able to format numbers using something similar to C's printf(). Meaning, I'd like to be able to specify

  • Comma separator every 3 S.F.
  • # of digits after decimal point
  • 0 padding before decimal point
  • etc.

For arguments sake, I'll give an example : I'm writing a stored proc in HSQLDB to create a human readable audit trail. An example row that I would like is:

Time                     Event
----                     -----
2014-02-10 14:54:10.855  Filled 50,000 at 13.3144 (66,5720.00 MXN), leaves 0.

The numerical values originate from DB columns (both integer and decimal). But currently I'm using CAST to convert these to VARCHAR, and I then concat them using ||. The actual output is:

Filled 50000.0E0 at 13.3144E0 (665720.0E0 MXN), leaves 0.0E0

I also have to worry about truncation of the whole message - I need to make sure that the length of the converted numbers don't exceed the allowed size of the Event column.

So I'd like to hear what peoples approaches are when doing something like this. One thing that comes to mind is that this could be written in a java stored proc, allowing the use of printf(). Is this the best way to go, or is there a nifty way to do it in SQL? Also, let's assume for the sake of argument that this needs to be part of the DB (i.e. querying the tables externally and then formatting the data is not an option).

Was it helpful?

Solution

This can be written in a Java or SQL FUNCTION.

In a SQL function, if you cast a number to DECIMAL(20,2) you will get the fixed number of 2 decimal points. Cast to BIGINT will give no decimal point. This solves the decimal point problem when you cast the result to VARCHAR(40). You need to write a function to insert the The commas in the string. The SUBSTRING function can be used to get the parts of the string and the || operator to concatenate them with the commas.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top