Double to String keeping trailing zero

后端 未结 3 1278
攒了一身酷
攒了一身酷 2020-12-10 18:11

I\'ve tried converting the double value into a string and using the Replace() method to replace the \',\' to \'.\'.

This works well but only when the

相关标签:
3条回答
  • 2020-12-10 18:24

    If this is in Java, check out the NumberFormat class's setMinimumFractionDigits() method.

    Example:

    double d1 = 2.5;
    double d2 = 5.0;
    
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(2);
    
    String d1s = nf.format(d1);
    String d2s = nf.format(d2);
    
    System.out.println("d1s: " + d1s + " and d2s: " + d2s);
    

    produces

    d1s: 2.50 and d2s: 5.00

    0 讨论(0)
  • 2020-12-10 18:32

    This would depend on the language. An example in C#

    d.ToString("0.00");
    

    Would produce a double with 2 decimal places nomatter the values (zero or otherwise).

    0 讨论(0)
  • 2020-12-10 18:41

    ...and in Fortran, you could do something like: :-)

          write(*,110) x
      110 format (F5.3)
    

    (guess we really have to know what language is being used...)

    0 讨论(0)
提交回复
热议问题