printf - format command of C that will not round of the value

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jerjer
    New Member
    • May 2008
    • 1

    #1

    printf - format command of C that will not round of the value

    i have a question
    please refer below..

    Example:

    #include <stdio.h>
    int main() {
    printf("%6.1f", 123456.123456);
    printf("\n%6.2f ", 123456.123456);
    printf("\n%6.3f ", 123456.123456);
    printf("\n%6.4f ", 123456.123456);
    }

    output :
    123456.1
    123456.12
    123456.123
    123456.1235

    at last output the result was 123456.1235 because it was rounded up.

    How to display this value by not rounding up?
    like 123456.1234 ?
  • arnaudk
    Contributor
    • Sep 2007
    • 425

    #2
    Formatted string conversions will always round as far as I know. The only way would be to truncate all decimals beyond the 4th:
    [code=c]
    #include <math.h>
    double truncate(const double val, const int d)
    {
    double rval = val * pow(10,d);
    rval = (double) floor(rval);
    return rval / pow(10,d);
    }

    int main()
    {
    double r =1.23456;
    printf("r = %f, r_4 = %1.4f, r_4t = %1.4f\n",r,r,tr uncate(r,4));
    return 0;
    }

    // Result: r = 1.23456, r_4 = 1.2346, r_4t = 1.2345
    [/code]

    Comment

    Working...