Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Format Specifier for Limiting Trailing Zeros to 1

Tags:

java

format

I'm looking for a format specifier to limit the number of trailing zeros after a decimal to just 1, but if they aren't all zeros then truncate to two.

Like so:

127.000000 -> 127.0

0.000000 -> 0.0

123.456 -> 123.45

I Have tried taking care of it with logic but it doesn't seem to work.

call my number result and use the following logic:

    if(result - (int)result == 0){
        output = String.format("%.1f\n",result);
    }
    else{
        output = String.format("%.2f\n,result);
    }

sometimes this logic works, and sometimes it doesnt. For example

(int)result - result == 0 is true for 0.000000

but false for 127.000000

Any ideas?

like image 966
tgabb Avatar asked Oct 15 '25 22:10

tgabb


2 Answers

What about NumberFormat?

NumberFormat formatter = NumberFormat.getNumberInstance(Locale.ROOT);
formatter.setMinimumFractionDigits(1);
formatter.setMaximumFractionDigits(2);
String s1 = formatter.format(127.000000);
String s2 = formatter.format(0.000000);
String s3 = formatter.format(123.456);
System.out.println(s1);     //prints 127.0
System.out.println(s2);     //prints 0.0
System.out.println(s3);     //prints 123.46
like image 51
Roman Danilov Avatar answered Oct 18 '25 16:10

Roman Danilov


Since you want at most two digits after the decimal point, you can first cut the rest out and then decide if you want to keep the last digit or not.

    float result = 127.8901f; //0.0000 
    String output = String.format("%.2f", result);
    if (output.endsWith("00")) output = output.substring(0,output.length()-1);
like image 32
jrook Avatar answered Oct 18 '25 16:10

jrook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!