开发者

format specifier for long double (I want to truncate the 0's after decimal)

I have a 15-digit floating-point number and I need to truncate the trailing zeros after the decimal point. Is there a format specifier for that?开发者_如何学C


%Lg is probably what you want: see http://developer.apple.com/library/ios/#DOCUMENTATION/System/Conceptual/ManPages_iPhoneOS/man3/printf.3.html.


Unfortunately in C there is no format specifier that seems to meet all the requirements you have. %Lg is the closest but as you noted it switched to scientific notation at its discretion. %Lf won't work by itself because it won't remove the trailing zeroes.

What you're going to have to do is print the fixed format number to a buffer and then manually remove the zeroes with string editing (which can STILL be tricky if you have rounding errors and numbers like 123.100000009781).


Is this what you want:

#include <iostream>
#include <iomanip>

int main() 
{
     double doubleValue = 78998.9878000000000;
     std::cout << std::setprecision(15) << doubleValue << std::endl;
}

Output:

78998.9878

Note that trailing zeros after the decimal point are truncated!

Online Demo : http://www.ideone.com/vRFlQ


You could print the format specifier as a string, filling in the appropriate amount of digits if you can determine how many:

sprintf(fmt, "%%.%dlf", digits);
printf(fmt, number);

or, just checking trailing 0 characters:

sprintf(fmt, "%.15lf", 2.123);
truncate(fmt);
printf("%s", fmt);

truncate(char * fmt) {
  int i = strlen(fmt);
  while (fmt[--i] == '0'  && i != 0);
  fmt[i+1] = '\0';
}


%.15g — the 15 being the maximum number of significant digits required in the string (not the number of decimal places)

 1.012345678900000 => 1.0123456789
 12.012345678900000 => 12.0123456789
 123.012345678900000 => 123.0123456789
 1234.012345678900000 => 1234.0123456789
 12345.012345678900000 => 12345.0123456789
 123456.012345678900000 => 123456.012345679
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜