CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 17 of 17
  1. #16
    Join Date
    Feb 2009
    Location
    Portland, OR
    Posts
    1,488

    Re: floating point number formatting question

    Very nice! I didn't know that * is a special symbol. You can probably shrink it down to even 2 lines of code if you consolidate the 'n' variable. And we can probably save some on CPU cycles if we replace second division (nValueMult100 &#37; 100) with (nValueMult100 < 100).

  2. #17
    Join Date
    Mar 2006
    Posts
    151

    Re: floating point number formatting question

    You might be able to gain control and flexibility if you print it as two integers:
    Code:
    #include <math.h>
    void NoTrailingZerosPrintf(double const dValue, unsigned short nDecimalPlaces)
    {
        int const nFactor    = static_cast<int>(pow(10.0, nDecimalPlaces));
        int const iFixed     = static_cast<int>(dValue * nFactor + (dValue > 0 ? 0.5 : -0.5));
        int       iFraction  = abs(iFixed % nFactor);
        while     (iFraction > 0 && iFraction % 10 == 0) { iFraction /= 10; --nDecimalPlaces; }
        printf    (iFraction == 0 ? "%d\n" : "%d.%0*d\n", iFixed / nFactor, nDecimalPlaces, iFraction);
    }
     
    int main(int argc,char* argv[])
    {
        NoTrailingZerosPrintf(1.0000   , 2);  // Test case 1.1
        NoTrailingZerosPrintf(1.30     , 2);  // Test case 1.2
        NoTrailingZerosPrintf(1.32     , 2);  // Test case 1.3
        NoTrailingZerosPrintf(1.38     , 2);  // Test case 1.4
        NoTrailingZerosPrintf(1.322    , 2);  // Test case 1.5
        NoTrailingZerosPrintf(1.325    , 2);  // Test case 1.6
        NoTrailingZerosPrintf(-37.09   , 3);  // Test case 2.1
        NoTrailingZerosPrintf(-37.09   , 1);  // Test case 2.2
        NoTrailingZerosPrintf(-37.00005, 4);  // Test case 2.3
        NoTrailingZerosPrintf(-37.00004, 4);  // Test case 2.4
        NoTrailingZerosPrintf(-37.00005, 5);  // Test case 2.5
        NoTrailingZerosPrintf(1.998    , 2);  // Test case 3.1
        return 0;
    }
    Output:
    1
    1.3
    1.32
    1.38
    1.32
    1.33
    -37.09
    -37.1
    -37.0001
    -37
    -37.00005
    2

Page 2 of 2 FirstFirst 12

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured