Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: String format with Double value

Tags:

I need to create a String using the Formater to display some double float values. I'm not clear on how to code it. Here is what I have:

Double dWeightInKg = 100; Double dWeightInLbs = 220: String headerText = String.format("%.0f kg / %.0f lbs",Double.toString(dWeightInKg) , Double.toString(dWeightInLbs)); 

I'm looking for the following output:

100 kg / 220 lbs 

I get a runtimeexception - badArgumentType(formater) on my String.format line.

like image 482
wyoskibum Avatar asked Aug 29 '12 01:08

wyoskibum


People also ask

How to format double Value Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.

What is. 2f in Java?

The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

What is %d in string in Java?

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is: The value of i is: 461012. The printf and format methods are overloaded.


2 Answers

%.0f is the format string for a float, with 0 decimal places.

The values you're passing to String.format are String, String when it needs to be Double, Double.

You do not need to convert the doubles to strings.

String headerText = String.format("%.0f kg / %.0f lbs", dWeightInKg, dWeightInLbs); 
like image 62
JustinDanielson Avatar answered Sep 17 '22 17:09

JustinDanielson


This should work,

DecimalFormat df = new DecimalFormat("#.##"); private String convertToFormat(double value){      return df.format(value); } 
like image 34
VendettaDroid Avatar answered Sep 21 '22 17:09

VendettaDroid