2
int main(){
    std::string text = "15555555.2587";
    std::stringstream ss;
    double number;
    ss << text;
    ss >> number;
    std::cout << std::fixed << std::setw( 11 ) << std::setprecision( 6 ) 
      << std::setfill( '0' ) << number<<endl;

    return 0;
}

Output of the above program is 15555555.0000

it truncates the value after the decimal point.

how do I get the correct value?

helb
  • 7,609
  • 8
  • 36
  • 58
Ritesh Banka
  • 173
  • 1
  • 1
  • 13
  • 1
    I think it depends on some local settings. Try with replacing the `.` with `,`. It's a guess, but.. – Kiril Kirov Nov 14 '13 at 08:42
  • 1
    By default double values are displayed to 6 figures. Look up setprecision. – Alan Stokes Nov 14 '13 at 08:46
  • if I set the value of sting to 15555555.2587, the program returns 15555555.0000 – Ritesh Banka Nov 14 '13 at 08:54
  • 1
    As Kiril Kirov said, it might be a locale issue if precision does not help. Possibly the locale set on your system uses some other symbol instead of '.' (',' would be a good guess for several European languages e.g. German). Which locale are you using? – Hulk Nov 14 '13 at 09:20
  • My system is using '.' for decimal notation – Ritesh Banka Nov 14 '13 at 09:24
  • for 155555.2587 its output is correct, but for 15555555.2587 its output is 15555555.0000 – Ritesh Banka Nov 14 '13 at 09:41
  • @RiteshBanka Well then, it _is_ a duplicate of http://stackoverflow.com/questions/11989374/floating-point-format-for-stdostream – helb Nov 14 '13 at 10:00
  • I used the same command to print the result but I am getting wrong output so thought of posting it as a new question – Ritesh Banka Nov 14 '13 at 10:13
  • It would be easier if you didn't keep changing the question. What happens if you increase precision now? Have you considered reading the documentation? – Alan Stokes Nov 14 '13 at 20:08

2 Answers2

3

You have correct value in number as expected. The problem is you should print it by cout in this way:

std::cout << std::fixed << std::setprecision(4) << number;

Output

155555.2587
masoud
  • 55,379
  • 16
  • 141
  • 208
1

As Alan Stokes said, streams are configured to print floating-point values with 6 decimal digits by default. You could modify this behaviour through stream manipulators like std::setprecision():

int main()
{
    float pi = 3.141592654;

    std::cout << std::fixed << std::setprecision( 4 ) << pi << std::endl;
}

The code above prints:

3,1416

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
Manu343726
  • 13,969
  • 4
  • 40
  • 75