Java formating Float to String with precision in two numbers - java

I want to convert Float into String, but I've got a problem with precision
I want to see something like 5.50 in String format.
If I use
String price = new DecimalFormat("#.##").format(ClientOrder.TOTAL_PRICE);
totalPriceTV.setText("" + price + " " + OptionsApp.CURRENCY);
I will get price looking like an integer, or like 5.5
ClientOrder.TOTAL_PRICE is a float number
So how to get String with 2 numbers after point?

You can write something like this too:
String price = String.format("%.2f", ClientOrder.TOTAL_PRICE);

The right pattern is "#.00".
String price = new DecimalFormat("#.00").format(ClientOrder.TOTAL_PRICE);
totalPriceTV.setText("" + price + " " + OptionsApp.CURRENCY);

You can use String.substring(int, int) with String.indexOf(String).
String totalPrice = "5.50158941";
String price = totalPrice.substring(0, totalPrice.indexOf(".") + 3);

Related

way to convert a decimal formatted value to the original value

Initially I may have a double, float or similar type value.
I'm using DecimalFormat to format this values as "##,###.000".
That formatted value, which is now a String I want to return back to it's original value of a primitive type.
Currently, I'm solving parsing issue by replacing comma with empty character. doubleToString.replace(",", "")
However, later I may change the formatPattern and replace it with dot instead of comma "##.###.00" or perhaps specify a different format.
My question is, as title says, is there a way to parse this value back to the original value (initial type and value), or I have to manually handle this by replacing etc.?
My code example:
double initialValue = 12345;
System.out.println("Initial value: " + initialValue);
final DecimalFormat decimalFormat = new DecimalFormat("##,###.000");
// double to string
final String doubleToString = decimalFormat.format(initialValue);
System.out.println("Double to String: " + doubleToString);
// string to double
final double stringToDouble = Double.parseDouble(doubleToString.replace(",", ""));
System.out.println("String to Double: " + stringToDouble);

DecimalFormat - Format decimal to preserve variable amount of trailing zeros

I have a situation where I need to preserve the number of decimal places for a number when formatting to a String using DecimalFormat, specifically for trailing zeros. I need to use DecimalFormat because I also need to avoid scientific notation for large numbers, and as seen here, this is the best way to do so. However, as you can see in that post, the code provided also removes trailing zeros, whereas I would like to preserve them.
1.00 -> "1.00"
1.000 -> "1.000"
I've seen a lot of questions that involve a fixed number of decimal places, but in my situation I need to account for a variable amount of decimal places. I looked into counting the number of decimal places, but since my input can also be a Double (in addition to BigDecimal), there appears to be no reliable way to count the digits after the decimal point for all numbers. Double.toString() does not work since Doubles break into exponential notation for very small and very big numbers. See here for more info regarding why it is difficult to count the number of decimal places in a double.
"Preserve" trailing zeros?
A double value doesn't know how many trailing zeroes you want to see. It is just a number, and 1.00 and 1.000 are the same number, i.e. the number 1. What you are asking cannot be done with a double value.
Now, BigDecimal does remember the number of trailing zeroes, so if you want to print a BigDecimal value, retaining the scale of the number, but ensuring it never prints in scientific notation, don't use a DecimalFormat, but instead use toPlainString():
Returns a string representation of this BigDecimal without an exponent field.
UPDATE
If you want to print a double value with as many decimal fraction digits as needed (i.e. no trailing zeroes), and want to make sure it never prints in scientific notation, use a DecimalFormat with very high MaximumIntegerDigits and very high setMaximumFractionDigits.
"Very high" means values exceeding the range of a double, so 999 is a good "round" number, though 330 would be high enough.
Test
DecimalFormat fmt = new DecimalFormat("0");
fmt.setMaximumIntegerDigits(330);
fmt.setMaximumFractionDigits(330);
System.out.println("0.0123400 = " + 0.0123400 + " = " + fmt.format(0.0123400));
System.out.println("123400.00 = " + 123400.00 + " = " + fmt.format(123400.00));
System.out.println("NaN = " + Double.NaN + " = " + fmt.format(Double.NaN));
System.out.println("-INFINITY = " + Double.NEGATIVE_INFINITY + " = " + fmt.format(Double.NEGATIVE_INFINITY));
System.out.println("+INFINITY = " + Double.POSITIVE_INFINITY + " = " + fmt.format(Double.POSITIVE_INFINITY));
System.out.println("MIN_NORMAL = " + Double.MIN_NORMAL + " = " + fmt.format(Double.MIN_NORMAL));
System.out.println("MIN_VALUE = " + Double.MIN_VALUE + " = " + fmt.format(Double.MIN_VALUE));
System.out.println("MAX_VALUE = " + Double.MAX_VALUE + " = " + fmt.format(Double.MAX_VALUE));
Output
0.0123400 = 0.01234 = 0.01234
123400.00 = 123400.0 = 123400
NaN = NaN = �
-INFINITY = -Infinity = -∞
+INFINITY = Infinity = ∞
MIN_NORMAL = 2.2250738585072014E-308 = 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014
MIN_VALUE = 4.9E-324 = 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000049
MAX_VALUE = 1.7976931348623157E308 = 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Either double (no precision, always approximating values), or BigDecimal.
Use BigDecimal as new BigDecimal("2.00") defining the correct scale (precision) of two digits. You can set the scale programmatically.
For database and calculation (like financial) BigDecimal is fine.
The scientific representation on output can be avoided in BigDecimal.toPlainString().
For double one could format with
s = String.format("%10.2f", 13.5789); // " 13.58"
All this is with a decimal point and no thousands separators.
Internationalized (localized) software will use a MessageFormat with a Locale (explicit or the default platform locale).
Locale.setDefault(new Locale("bg", "BG"));
s = MessageFormat.format("Number: {0, number, #.##}, "
+ "amount: {1, number, currency}",
42.125, 19.99);

Force double to display 2 decimal points [duplicate]

This question already has answers here:
Best way to Format a Double value to 2 Decimal places [duplicate]
(2 answers)
How to round a number to n decimal places in Java
(39 answers)
Closed 5 years ago.
Bit of a silly one, but just to clarify I know I can format the output to a string and then format the string in a variety of ways to achieve this but I need the return value to stay as a double as it has multiple uses.
So basically I have a LinkedList that i am reading values in from that was formatted as a double when imported. I am then using the sum of these values to essentially calculate a total which I am using in a toString function and a couple of other places.
My issue is if there are trailing zeros they are trimed so the values is as small as possible. e.g: 3.50 -> 3.5, 0.00 -> 0.0 and so on.
public double totalCost(){
double total = 0.00;
for(Ingredient cost : ingredients){
total += cost.ingredientCost();
}
return total;
The code above is the sum code.
public String toString(){
return crust() + " pizza with " + toppings() + " and " + sauce() + ": $" + totalCost();
}
And this is my toString function.
Any guidance would be awesome.
I think this will help you:
public String toString(){
return crust() + " pizza with " + toppings() + " and " + sauce() + ": $" + String.format( "%.2f", totalCost());
}

formatting toString method using String.format

required output:
Code: 123 Title: BookA Fees(SGD): $20.00
Loan Duration: 3 wks
return String.format("%-20s%-20s%\n", "Code: " + code, "Title: " + title, "%.2f\nFees(SGD): $" + fees, "Lesson Duration: " + lessonDuration + "wks");
it only returns only the first 3 (code, title, fees) but not loan duration. also where do i put in %.2f for fees so that it will always be of 2 decimal place?
Your question asks about "Loan Duration", but your example code uses "Lesson Duration". That could be your problem.
That %.2f should work for setting two decimal places. How is it behaving?
When you use String.format, you usually just pass your variables in and use the correct percent signs for your variables' types. For instance, if you want to format an integer, you use %d: String.format("Here is an integer: %d", myInt). For strings, you use %s, and for doubles, you use %f (with .2 to indicate the number of decimal places as you've already found out. You put all of your formatting in the first string parameter. All you have to do then is this:
String code = "123";
String title = "BookA";
double fees = 20.943;
int lessonDuration = 3;
String str = String.format("Code: %s\nTitle: %s\nFees(SGD): $%.2f\nLesson Duration: %d wks",
code,
title,
fees,
lessonDuration);
You should go read this article here so you understand formatting in Java and don't fail your test.

Convert Floating point double to non floating point string

I have the following number:
1.0645208E10, which is in my case a double value. I would like to convert it into 106.45.
Any recommendation how to get 106.45?
I appreciate your answers!
You can try this:
double bigDouble = 1.0645208E10;
String strDouble = String.format(Locale.ENGLISH, "%.2f", bigDouble/100000000);
System.out.println(strDouble);
It will give you 106.45
But be aware of the fact that the output has nothing to do with the original value!! Is one hundred million times smaller...
Any recommendation how to get 106.45?
If you want to get only output then you can do following.
Double d = 1.0645208E10;
String s = d.toString().replace(".", "");//Converts into string and removes dot (.)
String s1 = s.substring(0, 5);//it gets only first 5 characters
String s2 = s1.substring(0, 3) + "." + s1.substring(3, 5);//it adds decimal point after first 3 character
System.out.println("Expected Output: " + s2);

Categories