2

How to get exactly 2 digits after the decimal point approx in sage? If I do the following:

sage: k = 0.0006
sage: k.n(digits = 2)
0.00060

I get too many digits. In this case I would want 0.00 as the solution.

Mahathi Vempati
  • 1,238
  • 1
  • 12
  • 33

1 Answers1

2

Python formatting makes it easy to print floats with two decimal digits.

So we can turn k into a Python float and use Python string formatting.

sage: k = 0.00060
sage: print('{:0.2f}'.format(float(k)))
0.00

sage: k = 1234.5
sage: print('{:0.2f}'.format(float(k)))
1234.50

In Python3-based SageMath, one can even use f-strings:

sage: print(f'{float(k):0.2f}')
1234.50
Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27