【发布时间】:2020-10-05 22:51:32
【问题描述】:
当我在 PostgreSQL 11.8 中使用 json_build_object() 函数构建 json 时,我试图截断 双精度 值,但没有成功。更准确地说,我试图将 19.9899999999999984 数字截断为仅两位小数,但确保它不会将其四舍五入到 20.00(它就是这样做的),而是将其保持在 19.98 。
顺便说一句,到目前为止我尝试过的是使用:
1) TRUNC(found_book.price::numeric, 2) 我得到价值 20.00
2) ROUND(found_book.price::numeric, 2) 我得到了价值 19.99 -> 到目前为止这是最接近的价值,但不是我需要的
3)ROUND(found_book.price::double precision, 2) 我得到了
[42883] 错误:函数 round(双精度,整数)不存在
这也是我正在使用的整个代码:
create or replace function public.get_book_by_book_id8(b_id bigint) returns json as
$BODY$
declare
found_book book;
book_authors json;
book_categories json;
book_price double precision;
begin
-- Load book data:
select * into found_book
from book b2
where b2.book_id = b_id;
-- Get assigned authors
select case when count(x) = 0 then '[]' else json_agg(x) end into book_authors
from (select aut.*
from book b
inner join author_book as ab on b.book_id = ab.book_id
inner join author as aut on ab.author_id = aut.author_id
where b.book_id = b_id) x;
-- Get assigned categories
select case when count(y) = 0 then '[]' else json_agg(y) end into book_categories
from (select cat.*
from book b
inner join category_book as cb on b.book_id = cb.book_id
inner join category as cat on cb.category_id = cat.category_id
where b.book_id = b_id) y;
book_price = trunc(found_book.price, 2);
-- Build the JSON response:
return (select json_build_object(
'book_id', found_book.book_id,
'title', found_book.title,
'price', book_price,
'amount', found_book.amount,
'is_deleted', found_book.is_deleted,
'authors', book_authors,
'categories', book_categories
));
end
$BODY$
language 'plpgsql';
select get_book_by_book_id8(186);
如何实现仅保留前两位十进制数字 19.98(非常感谢任何建议/帮助)?
P.S. PostgreSQL 版本是 11.8
【问题讨论】:
-
您的确切 PostgreSQL 版本是多少?我无法在 12.3 中重现。
found_book.price的数据类型是什么? -
@pifor:它是 PostgreSQL 11.8
-
您必须添加一个完整的 SQL 语句来显示不需要的舍入。我不确定你到底在做什么。
-
found_book.price的原始数据类型是什么?将结果传递给json_build_object应该没有关系。 -
@Bergi: 这是
double precision(found_book.price)
标签: json postgresql rounding plpgsql truncated