Example:
I have a variable A that has a value of 5.123.
我有一个变量A,其值为5.123。
A * 2 = 10.246
A * 2 = 10.246
I want calculate with only the 2 numbers after the decimal point (.12), like that:
我想用小数点后面的2个数字(.12)计算,就像那样:
A * 2 = 10.24
A * 2 = 10.24
Is there any solution for this?
这有什么解决方案吗?
2 个解决方案
#1
0
One option could be to truncate it:
一种选择可能是截断它:
value = (double) ((int)(value * 100))/100;
Here is a sample:
这是一个示例:
double valueOne = 2.34256;
cout<<valueOne<<endl;
double valueTwo = (double)((int)(valueOne*100))/100;
cout<<valueTwo<<endl;
Output:
2.34256
2.34
#2
0
I am not sure how fancy you need to be with your numbers but the following strategy should work.
我不确定你需要多少花哨的数字,但以下策略应该有效。
double A = 5.123;
int A1 = A*100; // A1 is 512
int A2 = A1*2; // A2 is 1024
A = 0.01*A2; // A is 10.24
#1
0
One option could be to truncate it:
一种选择可能是截断它:
value = (double) ((int)(value * 100))/100;
Here is a sample:
这是一个示例:
double valueOne = 2.34256;
cout<<valueOne<<endl;
double valueTwo = (double)((int)(valueOne*100))/100;
cout<<valueTwo<<endl;
Output:
2.34256
2.34
#2
0
I am not sure how fancy you need to be with your numbers but the following strategy should work.
我不确定你需要多少花哨的数字,但以下策略应该有效。
double A = 5.123;
int A1 = A*100; // A1 is 512
int A2 = A1*2; // A2 is 1024
A = 0.01*A2; // A is 10.24