铸造是否具有破坏性

铸造是否具有破坏性

本文介绍了铸造是否具有破坏性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,我知道我们不应该在没有像bcmath这样的东西的浮动体上进行数学,而是仅仅是一个用于浮动破坏性的字符串的方法。



表达式如(float)'5.111'=='5.111',始终为true?或者演员本身会将其更改为像$ code> 5.1110000000000199837 一样的数字转换?



主要原因是,正如我使用(int)来转义进入数据库的整数值,I想要以相同的方式使用(float),而不必依赖引号和我的转义函数。

解决方案

,铸造成浮动几乎总是破坏性。



在你的例子中,以二进制表示的5.111是:

  101.00011100011010100111111011111001110110110010001011010000111001 ... 

浮点数将存储23位数:

  101.0001110001101010011 
(5.1109981536865234375)

双重将存储52位数:

  101.0001110001101010011111101111100111011011001000101 
(5.1109999999999988773424774990417063236236572265625)


$ b $在这种情况下,没有什么区别。然而,在更大的数量,它可以影响你显示的内容。



例如:



1025.4995



double:

  10000000001.011111111101111100111011011001000101101 
(1025.499499999999898136593401432037353515625)

float:

  10000000001.011111111101 
(1025.499267578125)

您可以看到在大约8位数后,精度开始急剧下降。 >

双人将轮到 1025.4995 ,而float将为 1025.4993


In PHP, I know we shouldn't do math on floats without things like bcmath, but is the mere act of casting a string to float destructive?

Will expressions like (float)'5.111' == '5.111', always be true? Or will the cast itself change that to something like 5.1110000000000199837 as the number is converted?

The main reason is, just as I use (int) to escape integer values going into a database, I would like to use (float) in the same way, without having to rely on quotes and my escape function.

解决方案

NO, Casting to a float is almost always destructive.

In your example, 5.111 represented in binary is:

101.00011100011010100111111011111001110110110010001011010000111001...

A float would store 23 digits:

101.0001110001101010011
(5.1109981536865234375)

A double would store 52 digits:

101.0001110001101010011111101111100111011011001000101
(5.1109999999999988773424774990417063236236572265625)

In this case, there wouldn't be a difference. However, in larger numbers, it can affect what you display.

For example:

1025.4995

double:

10000000001.011111111101111100111011011001000101101
(1025.499499999999898136593401432037353515625)

float:

10000000001.011111111101
(1025.499267578125)

You can see the precision starts to drop off dramatically after around 8 digits.

The double would round to 1025.4995 whereas the float would be 1025.4993

这篇关于铸造是否具有破坏性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 10:12