注意:这可以在Server、Oracle、DB2或MySQL数据库中运行。但是对于这个例子,我只是使用Server。但是,该解决方案必须足够通用,可以应用所有提到的数据库。
在Server中,我有一个定义为decimal(32, 16)的列,因为该列必须能够存储可能较大或精确的值。然而,它也可能存储较小或不精确的值。但是,当我选择BigDecimal时,返回的是尾随的零,这些零不在原始值中。我认为这是因为我的列定义允许高精度。
我不希望任何值被存储或返回与“发明”的比例尺/精度,但我仍然需要允许较大的规模/精度。
// ... set up ...
// precision 2, scale 2
BigDecimal bdInsert = new BigDecimal("0.51");
preparedStatement.insertBigDecimal(1, bdInsert);
// ... insert/commit ... select ...
// precision 0, scale 16 <-- Grrrrrrr!
BigDecimal bdResult = resultSet.getBigDecimal(1);
System.out.println(bdResult);
// prints "0.5100000000000000" <-- Grrrrrrr!Server是否没有存储插入的BigDecimal的精度和规模,或者JDBC没有发送或选择?
我不能直接截断零,因为一个BigDecimal可能是用尾随零存储的,以表明它是精确的。
// "0.510000" indicating that this value is accurate to the 6th place
BigDecimal bdPrecise = new BigDecimal("0.510000");
preparedStatement.insertBigDecimal(1, bdPrecise);
// precision 0, scale 16
BigDecimal bdResult = resultSet.getBigDecimal(1);
System.out.println(bdResult);
// prints "0.5100000000000000" loses information
System.out.println(bdResult.stripTrailingZeros());
// prints "0.51", loses information
// What I want is "0.510000"是否有一种方法,可以通过Server或JDBC获得原始BigDecimal?的规模/精度
请不要告诉我我需要单独写一篇专栏来存储这些信息.
我想另一种选择是插入/选择BigDecimals作为String,然后像new BigDecimal(val)一样从字符串中解析它。但我更喜欢以十进制的形式存储。
谢谢。
发布于 2018-03-02 16:59:10
下面的代码演示Server中的sql_variant数据类型。(以及如何显示有关表达式的数据类型信息。)因为解决方案需要应用于任何能够保存位的东西,所以它不会解决所有的问题,但它可能有一定的价值。
我怀疑唯一能够跨“所有”平台工作的解决方案是一个字符串,可能包含具有显式精度的XML。
declare @Samples as Table ( Value sql_variant );
insert into @Samples ( Value ) values
( Cast( 3.14 as Decimal( 10, 2 ) ) );
insert into @Samples ( Value ) values
( Cast( 3.14 as Decimal( 10, 3 ) ) );
insert into @Samples ( Value ) values
( Cast( 3.14 as Decimal( 10, 4 ) ) );
insert into @Samples ( Value ) values
-- NB: Both values are inserted with scale 5 when they are included in a single INSERT.
( Cast( 42 as Decimal( 10, 1 ) ) ),
( Cast( 42 as Decimal( 10, 5 ) ) );
insert into @Samples ( Value ) values
( Cast( 1.618 as Decimal( 10, 6 ) ) );
insert into @Samples ( Value ) values
( 'Edgar' );
select Value, SQL_Variant_Property( Value, 'BaseType' ) as BaseType,
SQL_Variant_Property( Value, 'Precision' ) as Precision,
SQL_Variant_Property( Value, 'Scale' ) as Scale
from @Samples;(然后是钢铁厂,他们想要在英寸和十六英寸之间有一个圆点,例如23 3/4英寸被显示为"23.12“。如何处理"36.1“和"36.10”在投入和产出方面与9/16不同?( Oy.)
https://stackoverflow.com/questions/49073362
复制相似问题