Float values to String in Postgresql
Asked Answered
S

3

10

I'm using PgSQL 9.1.

SELECT 5.1::text 

is working fine with output '5.1' in PgAdmin3, but with JDBC Prepared statement EXEC SQL, the result always as '5.0999999'.

Of source SELECT to_char(5.1, '9.9') will work, however this is not what I want. I want to get '5' in the case of 5.0 without decimal point, so I just stay on the ::text conversion.

My assumption is there might be some session environment settings affected to this conversion somewhere, but I can't figure out how to find.

I know this is just a silly question... please help.

Suburbia answered 17/2, 2015 at 2:36 Comment(0)
S
9

I think I found a solution. Try to cast into numeric type first...

SELECT (5.1::numeric)::text 

Please add your answer if you have a better solution.

Suburbia answered 17/2, 2015 at 3:32 Comment(0)
G
1

Do the following:

select cast(5.1 as text)
Grolier answered 17/2, 2015 at 15:23 Comment(0)
H
1

In 2024 for Postgres 13.2 it works best as

SELECT (5.1::real)::text

For example, let's take an field test numeric(32,4) not null default 0. Then:

SELECT t.test FROM test_table t
-- 5.1000
SELECT t.test::text FROM test_table t
-- 5.1000
SELECT t.test::numeric::text FROM test_table t
-- 5.1000
SELECT t.test::real::text FROM test_table t
-- 5.1
Helgahelge answered 14/3 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.