Happo
Happo

Reputation: 311

Floating Point with 2 Digits after Point

I will Format a Floating Point Number in android with 2 Digits after the point. I search for a Example but i din´t find one.

Can some one help me.

Upvotes: 31

Views: 41945

Answers (3)

Tigran Babajanyan
Tigran Babajanyan

Reputation: 2025

In answer above it always will return 2 deciaml

examples with String.format("%.02f", f)

2.5555 -> 2.55

2.5 -> 2.50

but do you need to get 2.50 for 2.5?

for avoid to get excessive 0, you can use this solution

val format = DecimalFormat("0.##")
return format.format(floatNum)

Upvotes: 3

Linh
Linh

Reputation: 60923

You can also use DecimalFormat

float f = 102.236569f; 
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
//double twoDigitsF = Double.valueOf(decimalFormat.format(f)); also format double value    

Upvotes: 13

Ryan Reeves
Ryan Reeves

Reputation: 10229

float f = 2.3455f;  
String test = String.format("%.02f", f);

Upvotes: 90

Related Questions