[英]how I can normal a double point number to a int number exacly?
I have a Client program by tcp connection that send data to a server. 我有一个通过TCP连接将数据发送到服务器的客户端程序。 In client I need send a normalized decimal number to server for normalization I Multiplier decimal number to 100,000 then send it to server but I get wrong number in server.
在客户端中,我需要将标准化的十进制数发送到服务器以进行标准化,将十进制数乘以100,000,然后将其发送到服务器,但是服务器中的编号错误。 for example.
例如。
double price;
I set it from Gui to 74.40 我从Gui设置为74.40
cout<<price; ---> 74.40
and when I serial my object I send 当我序列化对象时,我发送
#define Normal 100000
int tmp = price*Normal;
oDest<<tmp;
In wireshrk I see that client sent 7439999. 在wireshhrk中,我看到该客户端发送了7439999。
why this happened? 为什么会这样? how I can pervent this problem?
我该如何解决这个问题?
Don't store anything as a floating point value. 不要将任何内容存储为浮点值。 Use a rational number instead, or use a fixed point value.
请改用有理数,或使用定点值。 Floating point values (like
double
) basically "cheat" in order to fix a large range of possible values into a reasonable chunk of memory, and they have to make compromises in order to do so. 浮点值(如
double
)基本上是“作弊”,以便将较大范围的可能值固定到合理的内存中,并且为此必须做出妥协。
If you are storing a financial value, consider storing pennies or cents or whatever is the smallest denomination. 如果要存储财务价值,请考虑存储几美分或几分钱或最小的面额的东西。
This is due to floating point precision errors. 这是由于浮点精度错误。 You can add some rounding:
您可以添加一些舍入:
int tmp = (price + 0.5/Normal)*Normal;
由于浮点数无法精确表示十进制数,因此在将其转换为整数时需要四舍五入。
int tmp = price*Normal + 0.5;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.