Search code examples
c++11floating-pointdecimal-point

Can I do a calculation using only the 2 numbers after decimal point in c++?


Example:

I have a variable A that has a value of 5.123.

A * 2 = 10.246

I want calculate with only the 2 numbers after the decimal point (.12), like that:

A * 2 = 10.24

Is there any solution for this?


Solution

  • 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