How to cut decimal off without rounding in C

后端 未结 5 1959
无人共我
无人共我 2020-12-01 18:11

How do I cut off decimal places in C without rounding?

For example if the number is 4.48

it will just show 4.4

%.1f

相关标签:
5条回答
  • 2020-12-01 18:46

    This should work

    double d = 4.48;
    d *= 10.;
    int i = d;
    d = (double) i / 10.; 
    
    0 讨论(0)
  • 2020-12-01 18:54

    Here is a simple way:

    printf("%.1f",trunc(x*10.0)/10.0);
    
    0 讨论(0)
  • 2020-12-01 18:58

    If your compiler supports C99, you should be able to use trunc() and friends:

    float f = 4.56f;
    f = truncf(f * 10.0) / 10.0;
    
    0 讨论(0)
  • 2020-12-01 19:01
    float myval = 4.48;
    float tr = ((int)(myval*10)) / 10.0;
    
    0 讨论(0)
  • 2020-12-01 19:04

    You can (ab)use the fact that integer division truncates and doesn't round:

    float original = 4.48;
    
    int tmp = original * 10; // 44.8 truncated to 44
    
    float truncated = tmp / 10.0; // 4.4
    
    0 讨论(0)
提交回复
热议问题