printf %f with only 2 numbers after the decimal point?

前端 未结 8 1559
温柔的废话
温柔的废话 2020-11-28 14:14

In my printf, I need to use %f but I\'m not sure how to truncate to 2 decimal places:

Example: getting

3.14159

相关标签:
8条回答
  • 2020-11-28 14:51

    Use this

    printf ("%.2f", 3.14159);
    
    0 讨论(0)
  • 2020-11-28 14:55
    System.out.printf("%.2f", number);
    

    BUT, this will round the number to the nearest decimal point you have mentioned.(As in your case you will get 3.14 since rounding 3.14159 to 2 decimal points will be 3.14)

    Since the function printf will round the numbers the answers for some other numbers may look like this,

    System.out.printf("%.2f", 3.14136); -> 3.14
    System.out.printf("%.2f", 3.14536); -> 3.15
    System.out.printf("%.2f", 3.14836); -> 3.15
    

    If you just need to cutoff the decimal numbers and limit it to a k decimal numbers without rounding,

    lets say k = 2.

    System.out.printf("%.2f", 3.14136 - 0.005); -> 3.14
    System.out.printf("%.2f", 3.14536 - 0.005); -> 3.14
    System.out.printf("%.2f", 3.14836 - 0.005); -> 3.14
    
    0 讨论(0)
提交回复
热议问题