MySQL使用除法时如何保持精度?

时间:2018-06-21 05:35:33

标签: php mysql precision division bcmath

让我们说我们有在表中检索到的值,这些值是字符串,因此可以将它们分开。我们有这种报告,但是我不喜欢通过编程语言来处理它,而是通过1个sql查询来运行它以检索所有报告。

为使查询简短,请看下面的简单mysql查询。

Exception in thread "main" java.time.format.DateTimeParseException: Text '2018-04-17T22:57:29Z' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=0, NanoOfSecond=0, MilliOfSecond=0, InstantSeconds=1524005849},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at iplus.fwk.manifest.Test.main(Test.java:37)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=0, NanoOfSecond=0, MilliOfSecond=0, InstantSeconds=1524005849},ISO of type java.time.format.Parsed
at java.time.LocalDateTime.from(LocalDateTime.java:461)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MicroOfSecond=0, NanoOfSecond=0, MilliOfSecond=0, InstantSeconds=1524005849},ISO of type java.time.format.Parsed
at java.time.LocalDate.from(LocalDate.java:368)
at java.time.LocalDateTime.from(LocalDateTime.java:456)
... 4 more

上面的返回值select "68078004281240001301" / "1000000000000000000" from {a dummy table}; ,我们在小数点丢失了68.07800428124

已经尝试过0001301FORMAT()却无法正常工作,或者我错过了一些mysql函数吗?


但是在PHP中使用bcmath时,我们可以这样做

ROUND()

上面的值将为我们提供我们想要的$n = '68078004281240001301'; $d = '1000000000000000000'; bcdiv($n, $d, strlen($d) - 1);

的精确度

请记住,稍后我将使用它与过滤器一起进行报告。

1 个答案:

答案 0 :(得分:1)

我假设困难在于,当您将两个字符串相除-实际上是整数时,它不知道要使用的值的类型(如精度)。如果您改为将值强制转换为decimal type,则可以强制其以任意精度工作(最多65位数字)...

select "68078004281240001301" / "1000000000000000000", cast("68078004281240001301" as decimal(60,30))/ cast("1000000000000000000" as decimal(60,30))

给予...

"68078004281240001301" / "1000000000000000000"
68.07800428124

cast("68078004281240001301" as decimal(60,30))/ cast("1000000000000000000" as decimal(60,30))
68.078004281240001301000000000000