简体   繁体   中英

Double to String keeping trailing zero

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 trailing digits are not zero, I need zeros in my string, even if the value is 1234.0. This worked well for the decimal values. I have tried to convert the double to decimal but I lose the decimal digits if there are zeros.

I know I'm missing something. I would be grateful for some suggestions.

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).

...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...)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM