Format decimal values with String in Java - java

I am new to android and java programming, so please forgive me if this is an easy question. My problem is to add % in end of the decimal value. I will get double value and don't know how much digits after decimal point, i need to convert to two digits after decimal point and finally need to add % at last position. The problem is, I will format the double value only once. I have tried like this DecimalFormat ("#.##%"), but decimal points moved two digits forward. Please help me to get out of this problem.
Using DecimalFormat ("#.##%"),
Actual : 34.142545
Output : 3414.25%

If you use % in format, it means that you want to convert value to percentage, but you need to remember that value 1 in percentage world is equal to 100% so value you use will be automatically multiplied by 100. To avoid this behaviour you can change % into literal by quoting it with apostrophes '%'
new DecimalFormat("#.##'%'");

By adding the % in the format, you multiply by 100 and add the % character. This is why it looks like the decimal point moves.
You can use something like:
String output = new DecimalFormat("#.##").format(input) + "%";
An alternative is to divide by 100 before formatting:
String output = new DecimalFormat("#.##%").format(input / 100.0);

Related

Convert Float To String With Commas No Rounding Or Decimal Changes

I am trying to convert a float to a String and insert commas into the resulting String. I don't want to add/remove any zeroes, change the precision of the float, or do any kind of rounding. I want the String result to have the exact same digits as the original float, just with commas added. A locale agnostic solution would be preferred.
What I need:
public String convertFloat(float number) {
// return converted String with commas and no rounding or extra digits
}
Some input/output examples:
Given float: 1500
Result: "1,500"
Given float: 0.00210014
Result: "0.00210014"
Given float: 168874.00210014
Result: "168,874.00210014"
Given float: 168874.01
Result: "168,874.01"
Things I have tried:
String.valueOf(168874.00210014f) // Does not work for me because the result does not contain commas
String.format("%,f", 10.2f) // Does not work for me because it inserts a bunch of zeroes on the end
// The below does not work for me because the precision gets thrown off and the result ends up being: 14.1999998093 When it should be just: 14.2
NumberFormat f = NumberFormat.getInstance();
f.setMaximumFractionDigits(10);
System.out.println(f.format(14.2f));
// Result: 14.1999998093
// The below does not work for me because a bunch of random extra digits get thrown onto the end
DecimalFormat f = new DecimalFormat("#,###.##########");
System.out.println(f.format(100514.2f));
// Result: 100,514.203125
// The below does not work for me because it rounds to 2 decimal places
DecimalFormat f = new DecimalFormat("#,###.00");
System.out.println(f.format(100514.21351f));
// Result: 100,514.203125
// Does not work for me because it rounds to 2 decimal places.
String s = String.format("%,.2f", 10.2629f)
What I am trying to do seems so simple. How can I get the exact same digits just with commas added in the resulting string?
It's important to realize that a float has about 7 digits of decimal precision -- about, because decimal numbers can't be represented precisely.
Your example value of 100514.213512345f won't ever come back out the same way you put it in because the original value would necessarily have been truncated at a value somewhere in the neighborhood of 100514.2
I know you don't want any rounding, but it's the nature of floating point math on computers. Even if you use double precision, you just make the rounding smaller -- the issue of rounding doesn't go away.
By default its 6 digits.
There are few pointers that I found:-
Float is distorting the value after decimal while double is not. Hence, would recommend using double.
It's impossible to show as many as digits after decimal as there are in original number. Hence below is a workaround:
String string = String.format("%,.6654f", Math.abs(n)).replaceAll("0*$", "")
n is a double number not a float.
I have used 6654 as random max decimal digits that you could have in your number increase it if you need to.
This is kind of hack but you can replace preceding zeros
String.format("%,f", 10.2f).replaceAll("0*$","")
As for precision with big numbers you should use BigDecimal
Additionally you can remove last dot if its round number
String.format("%,f", new BigDecimal(100010f)).replaceAll("0*$","").replaceAll("\\.$","")
OP here,
None of these answers really worked for me. Turns out that in my case converting to double was not possible. So I decided to sacrifice the commas and just go with String.valueOf() approach
Acknowledging what others have already posted regarding the limited about of digits allowed in a float, here's a version that should work when you are within the limit and won't cut out consecutive 0s if they properly belong to the float. We're basically just splitting the input into 2 substrings and adding the comma formatting to the first half.
String input = String.valueOf(number);
int decimalIndex = input.indexOf(".");
String firstHalf = input.substring(0, decimalIndex);
String secondHalf = input.substring(decimalIndex, input.length());
String commas = String.format("%,d", Integer.parseInt(firstHalf));
return commas + secondHalf;
If you want to retain more precision then please use doubles instead of floats.

Convert double to double with one decimal point and one decimal place?

I want to round any double to a double with the format of one decimal point and one decimal place so 29575.347434 would be 2.3.
Tried doing this with decimalFormat but when i try #.# i just get a string in the format of 29575.3 with a , and i have no idea idea how to cut off all decimal points while keeping my value a double.
You could get the number as String, take the first digit and the digit after '.'. For non-negative numbers that would be
String s = Double.toString(29575.347434);
double d = Double.parseDouble(s.charAt(0) + "." + s.charAt(s.indexOf('.') + 1));
System.out.println(d); // 2.3
If the number can be negative, you would have to correct the code for the possible minus sign.
You could accomplish this by using the modulo operator %.
It looks like your decimal formatting is working with #.#. That will give you the whole number and one decimal place. You can then do your number 29575.3 % 10 and get 5.3.
Try this code and see:
System.out.println(29575.3d % 10);
Try the following:
Number(parseFloat(29575.347434).toFixed(1))
You could also pass a string , because parseFloat() would convert it to number, then trunkate to wished decimal (output is string again), then convert back to decimal by function Number().
Works for me.

Why do print and printf show different numbers of decimal places by default

As part of my degree I am required to take a programming course in Java; I am an experienced C# developer, so perhaps what I would expect from C# is conflicting with how Java actually works. The professor of the course couldn't give me a good reason why print and printf produce different results, so I have turned to the internet.
As the title implies, I am getting different output when I use printf and print in a very basic Java application. The user is prompted for three values: the number of starting organisms (double), the percent change in population (double), and the number of days the population will multiply (int). I then run a calculation and output the values to the screen like so:
for(int x = 1; x < days; x++)
{
startingOrganisms = startingOrganisms + (startingOrganisms * (increasePercent));
System.out.printf("%d\t\t%f\n", (x + 1), startingOrganisms);
}
The problem is that this produces different output than if I just do:
System.out.print((x + 1) + "\t\t" + startingOrganisms+ "\n");
The image below shows what is produced with the first code sample. My expectation is that both print and printf would yield the same result, but that is not the case. Can anyone explain what the difference is? Cursory searches of Google didn't turn anything up.
By default, printf shows 6 decimal digits
You can control the number of decimal digits to show by explicitly specifying the precision. For example, for 12 decimal digits you can do:
printf("%.12f", val);
API reference: http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#dndec
If you want to get equivalent output to System.out.println but for some reason want to keep using printf, then you can do the following:
System.out.printf("%d\t\t%f\n", (x + 1), Double.toString(startingOrganisms));
This is due to the fact that by default for double or float printf print number upto 6 decimal places. You need to specify the precision if you want to control how many decimal places you want to print via printf. System.out.println prints exact value of double/float without adding some default decimal points.
e.g.
double d = 1.0;
// it will print 1.000000
System.out.printf("%f\n", d);
//1.0
System.out.printf("%.1f", d);
//1.0
System.out.println(d);
print just prints out the message. printf prints out a formatted string so natuaraly you should consider them to use differently
When it comes to double and float , printf by default prints up to 6 decimal digits. So in order to amend that result you need to specify how many digits you want to print on your screen.The code above will print up to 10 digits.
for example :
printf("%.10f", val);

Decimal Format conversion issue

I'm using DecimalFormat in order to convert double to string like this:
DecimalFormat df = new DecimalFormat("###.###");
df.format(km);
The problem is, although the variable km has the value of 9.655195710258606E-5, the result of the df.format method returns 0 as string.But I expect something like 9.655 instead of 0.
Any help & suggestions will be appreciated
Thank you for your concern
It works as it should. The string "9.655" would be wrong. The value is actually 0.00009655 and if you round it to 3 decimal places you get "0".
To see some more digits, you can use more decimal places in the format #.###### or force scientific notation with a format like this #.###E0.
In the end of these numbers, the E(x) represents the exponent. E-5, means the exponent is -5, which means the actual number is 9.655 * (1/(10^5)).

What should i have to change in that function to get the 0.00 like effect?

For to get the fraction point value upto two decimal Point i use this function.
double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("##.##");
return Double.valueOf(twoDForm.format(d));
But While there is a value like "5.50" then with this function i got only "5.5".
Instead of that i want to get the 5.50 with the above function then what should i have to change ??
Please give me the Updated function or any suggestion to change the output like "0.00".
Thanks.
Your example works fine for rounding numbers to 2 digits. But you will lose trailing zeros, because numeric variables (double, float, ...) do not store any formating information.
If you want to see trailing zeros (like 5.50) you have to format the numbers on output:
DecimalFormat twoDForm = new DecimalFormat("#0.00");
System.out.println(twoDForm.format(d));
Use the format:
new DecimalFormat("#0.00")
When you use #, zero values display as absent. Using a 0 will ensure that either a digit or a 0 is displayed.
DecimalFormat.format returns a String (not a StringBuffer), which you are then getting the Double.valueOf(...). You then return the double value, which I assume when you print it uses it's own toString() to be displayed. You need to run the DecimalFormat.format on the double value returned.

Categories