Java String format float with and without 0 [duplicate] - java

This question already has answers here:
Is it possible to use String.format for a conditional decimal point?
(2 answers)
How to nicely format floating numbers to string without unnecessary decimal 0's
(29 answers)
Closed 3 years ago.
I have a float number, let's say:
Float number = 2.667f;
String.format("%.1f", number)
will produce:
2,7
but in case of
Float number = 2.0f;
it will produce:
2,0
is it possible to instruct String.format to avoid 0 after comma in case of integer numbers in order to receive for example 2 in the mentioned case.

You can use DecimalFormat with # symbol:
DecimalFormat df = new DecimalFormat("#.#");
System.out.println(df.format(2.1f)); // 2.1
System.out.println(df.format(2.0f)); // 2

Related

Printing out double with variable length after decimal point [duplicate]

This question already has answers here:
Use DecimalFormat to get varying amount of decimal places
(4 answers)
Closed 1 year ago.
I was searching for a solution of how to print double with variable length. Means: user will define how many digits he wants after the decimal point, but without success.
I've come to something like, but it doesn't work :
num - double
dec(length) - integer
System.out.printf("%.(%d)f\n", num, dec);
Are you looking for something like the following?
Maybe solution 2 is suitable for you.
Solution 1:
System.out.printf("%.2f", val); // "%.2f" it's a string so you can make it in several ways...eg: "%."+ dec + "f";
Solution 2:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2); // you can use int variable instead of 2.. eg: df.setMaximumFractionDigits(dec);
System.out.println(df.format(decimalNumber));

Java String.format() leading zeros and 1 decimal place [duplicate]

This question already has answers here:
Add leading zeroes to number in Java? [duplicate]
(5 answers)
Closed 4 years ago.
I need a string like 50 to appear as 050.0. I am using String.format, but I can't figure out how to do leading zeros and a single decimal place at the same time. So far, I have tried String.format("%3.2f", number);, but that isn't working as I still get 50.0 rather than 050.0
Use DecimalFormat to control the number of mandatory digits:
DecimalFormat df = new DecimalFormat("#000.0");
System.out.println(df.format(50)); // 050.0
where
Symbol Location Localized? Meaning
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
You can use StringBuilder class to create a string with number 0 and then append it with you number and insert the decimals at the end.
int num = 50; /*Your number*/
StringBuilder s_num = new StringBuilder("0");
s_num.append(num);
s_num.append(".0");
String f_num = s_num.toString();

How to get exact decimal value from bigdecimal in java [duplicate]

This question already has answers here:
"new BigDecimal(13.3D)" results in imprecise "13.3000000000000007105.."?
(5 answers)
Closed 6 years ago.
I am trying to get number of digits after decimal point in BigDecimal value.
BigDecimal big = new BigDecimal(1231235612.45);
String[] str = big.toPlainString().split("\\.");
System.out.println(" Decimal Value: " + str[1]);
Using this I am getting following output -
Decimal Value: 4500000476837158203125.
Actualy I want to display only 45 as per the original BigDecimal value (1231235612.45).
So, my expected output is Decimal Value: 45.
But, while conversion it adds more digits after decimal points.
Is there any method or code to get exact same value from BigDecimal?
Don't use the double Constructor of BigDecimal (See Javadoc, it is discouraged).
use String constructor
new BigDecimal("1231235612.45");
or use MathContext
new BigDecimal(1231235612.45, MathContext.DECIMAL64);

How to change a float into a String in Java? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
Is it possible to change a float value to a String? If possible, is it also possible to converting it to a String while rounding the number to the nearest integer?
For example if I have a float such as 2.335 then, can I change it to a String of value "2.335" or "2" (by rounding it)?
Use java Float class:
String s = Float.toString(25.0f);
if you want to round down a number, simply use the Math.floor() function.
float f = 2.9999f;
String s = Float.toString(Math.floor(f));//rounds the number to 2 and converts to String
first line rounds the number down to the nearest integer and the second line converts it to a string.
Another way of doing this is using the String.valueOf(floatNumber);
float amount=100.00f;
String strAmount=String.valueOf(amount);
To do this you can simply do
float example = 2.335
String s = String.valueOf(Math.round(example));
To convert a float to a String:
String s = Float.toString(2.335f);
Rounding can be done via
String.format("%.5g%n", 0.912385);
which returns 0.91239
For a more elaborate answer, see Round a number in Java
Your first requirement can be fullfilled with String.valueOf
float f = 1.6f;
String str = String.valueOf(f);
For roundoff you can use Math.round and not Math.floor. As Math.floor will convert 1.6 to 1.0 and not 2.0 while Math.round will roundoff your number to nearest integer.

Best way to Format a Double value to 2 Decimal places [duplicate]

This question already has answers here:
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 3 years ago.
I am dealing with lot of double values in my application, is there is any easy way to handle the formatting of decimal values in Java?
Is there any other better way of doing it than
DecimalFormat df = new DecimalFormat("#.##");
What i want to do basically is format double values like
23.59004 to 23.59
35.7 to 35.70
3.0 to 3.00
9 to 9.00
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00", meaning exactly two decimal places.
If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".
An alternative is to use String.format:
double[] arr = { 23.59004,
35.7,
3.0,
9
};
for ( double dub : arr ) {
System.out.println( String.format( "%.2f", dub ) );
}
output:
23.59
35.70
3.00
9.00
You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

Categories