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

前端 未结 8 1558
温柔的废话
温柔的废话 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:33

    I suggest to learn it with printf because for many cases this will be sufficient for your needs and you won't need to create other objects.

    double d = 3.14159;     
    printf ("%.2f", d);
    

    But if you need rounding please refer to this post

    https://stackoverflow.com/a/153785/2815227

    0 讨论(0)
  • 2020-11-28 14:34

    as described in Formatter class, you need to declare precision. %.2f in your case.

    0 讨论(0)
  • 2020-11-28 14:35

    Use this:

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

    You can try printf("%.2f", [double]);

    0 讨论(0)
  • 2020-11-28 14:50

    Try:

    printf("%.2f", 3.14159);

    Reference:

    http://www.cplusplus.com/reference/clibrary/cstdio/printf/

    0 讨论(0)
  • 2020-11-28 14:51

    You can use something like this:

    printf("%.2f", number);
    

    If you need to use the string for something other than printing out, use the NumberFormat class:

    NumberFormat formatter = new DecimalFormatter("#.##");
    String s = formatter.format(3.14159265); // Creates a string containing "3.14"
    
    0 讨论(0)
提交回复
热议问题