从十进制到字符串的类型转换 [英] type casting from decimal to string

查看:66
本文介绍了从十进制到字符串的类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

double var1 = 123789456.785;
double var2 = 123789457.898;
double subtr = var2-var1;
qDebug()<<"Diff=>"<<subtr<<"Var1=>"<<var1<<"Var2=>"<<var2;

//Converting double to QString
QString str1 = QString::number(var1);
QString str2 = QString::number(var2);

//String to doubel
double newVar1= str1.toDouble();
double newVar2= str2.toDouble();
double subtrNew = newVar2-newVar1;
qDebug()<<"New Diff=>"<<subtrNew<<"New Var1=>"<<newVar1<<"New Var2=>"<<newVar2;





输出是这个



Output is this

Diff=> 1.113 Var1=> 1.23789e+08 Var2=> 1.23789e+08
New Diff=> 0 New Var1=> 1.23789e+08 New Var2=> 1.23789e+08





因此,在从双字符串转换为字符串而不是从字符串返回到双倍之后,我失去了1.113的差异。在类型转换后它变为0.如何解决这个问题。专家意见是必需的。请。



So after typecasting from Double to string than back from string to double i lost the difference which is 1.113. after type casting it becomes 0. how to tackle this issue. experts opinion is required. please.

推荐答案

没有类型转换。你只是在调用转换函数。



阅读用过的函数的文档 QString :: number(double) [ ^ ]。



该函数还有两个可选参数,未传递时具有默认值。相关参数是定义精度的第三个参数(要打印到字符串的有效数字的数量)。这由调试输出显示:

两个字符串值只有6位有效数字,因此相同。



您现在可能会问为什么打印的double值也只有6个有效数字。出于同样的原因:

<<对于值,运算符在格式化值时也使用6个有效数字。如果你想要更多(或更少)的数字,你必须指定精度(使用C ++标准库它是 std :: setprecision())。



将浮点值打印到文本文件并在以后读取时有一些通用规则:



  • 最大必须知道所需的精度。
  • 以上述精度加上一个打印值。
  • 打印时使用'g'格式,以确保精度不会因大小而丢失
  • 不要指望打印的初始值与从字符串返回的二进制文件的二进制文件完全相同。
There is no type casting. You are just calling conversion functions.

Read the documentation of the used function QString::number(double)[^].

The function has two more optional parameters which have default values when not passed. The relevant parameter is the third one which defines the precision (the number of significand digits to be printed to the string). This is shown by your debug output:
Both string values have only 6 significand digits and are therefore identical.

You might now ask why the printed double values also have only 6 significand digits. It is for the same reason:
The stream << operator for double values uses also 6 significand digits when formatting the value. If you want more (or less) digits, you must specify the precision (with the C++ standard library it is std::setprecision()).

There are some general rules when printing floating point values to text files and reading them in later:

  • The max. required precision must be known.
  • Print values with the above precision plus one.
  • Use the 'g' format when printing to ensure that the precision is not lost for very large and small numbers.
  • Don't expect that the initial value that has been printed is binary identical to the one get back from string to double.


请阅读 https://docs.oracle.com/cd/E19957-01 /806-3568/ncg_goldberg.html [ ^ ]。


这篇关于从十进制到字符串的类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆