This question already has answers here:
How to print a float with 2 decimal places in Java?
(18 answers)
Closed 7 years ago.
So let's say I have a simple array of float numbers
[0.315023, 1.0, 0.12345, 0121111]
And call it arr1.
I need to take this array and turn it into this:
[0.3150, 1.0000, 0.1234, 0.1211] *Please note that 1.0 is now 1.0000 and 0.3150 has a 0 at the end
I have tried using a for loop to iterate through the array and rounding the numbers as follows:
// i representing a number in the arr1; let's imagine that "newNum" replace the original numbers in arr1
float newNum = Math.round(i*10000.0000)/10000.0000;
What will result is following:
[0.315, 1.0, 0.1234, 0.1211]
As you can see, the first item is missing the 0 at the end, and the second item is missing a lot of zeros at the end.
I have tried to use DecimalFormat, but it doesn't work with the float array; also I am not trying to format decimals, I am rounding them. (although I have tried the round first then format second; which didn't work because of difference in datatype).
PLEASE for the love of God, help me. This is like the last thing I need to complete for my project. I am so close! Thank you so much in advance!
*PS: I need to make sure the array remains FLOAT; I need to use the data in the array later on.
DecimalFormat f = new DecimalFormat("##.0000");
System.out.println(" output : "+ f.format(2.56));
Follows java docs for format data
Use this:-
DecimalFormat twoDForm = new DecimalFormat("#.####");
double d = Double.valueOf(twoDForm.format(newNum));
Related
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 1 year ago.
Right now, Java is printing 7.1781566186590595E-6. I want it to print 7.17E-6.
I searched this up, but I only found how to reduce digits without scientific notation (so it will end up like 0.00 because the number is small).
Use format specifier "%.3g", tutorial here
float f = 7.1781566186590595E-6f;
System.out.format("%.3g", f);
Output
7.18e-06
Note, you mentioned 7.17E-6 in your question as desired output, but that's not correctly rounded - should be 7.18e-06
You can use String.format method to format and create your String, than you can use it like any String.
Therefore the "%.3g" format should be used like this:
double myDouble = 1/12345678d;
System.out.println(String.format("%.3g", myDouble));
Will result in: 8,10e-08.
Note: The ".3" in the format specifies the precision. In case you want more or less digits you can simply change the number to your needs like e.g. "%.5g" in case you want two extra digits.
You can also exchange the small "g" with "G" it'll print a capital "E" instead of the small "e".
In case you prefer the "." instead of the "," as a separator you can additionally explicitly specify the local to be used in the formatter like the following:
double myDouble = 1/12345678d;
System.out.println(String.format(Locale.ENGLISH, "%.3g", myDouble));
Will result in: 8.10e-08.
More information can be found in the JavaDoc of String.format here.
EDIT:
Interesting in your case:
When you use the format string as above (with the 'g') "%.3g" it'll round your value in the mathematical correct way. When you change the format string and use it with an 'e' "%.3e" it'll not round it and treat your number as a literal:
Code:
double myDouble = 7.1781566186590595E-6d;
System.out.println(String.format(Locale.ENGLISH, "%.3e", myDouble));
System.out.println(String.format(Locale.ENGLISH, "%.3g", myDouble));
Result:
7.178e-06 // using "%.3e" => literal, therefore not rounded
7.18e-06 // using "%.3g" => rounded
This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 7 years ago.
This is my array c:
[-33,-22,-11,-5,-4,-3,-2,-1,6,7,8,9,10,11,44,55,66,77,88]
I was able to find the sum by doing this and it worked:
System.out.println(Arrays.stream(c).sum()));
I tried a similar approach to get the average:
System.out.printf("%.2f",(Arrays.stream(c).sum()/c.length));
I got an IllegalFormatConversionException for that though.
When I manually do the average on a calculator, it should come out to 15.78947...but I only want to round 2 places after the decimal. I have tried other statements but those kept giving be 15 as the average and cutting the decimals off. I need to compute the average within the print statement. How can I do this?
I want my output to look like this: 15.79
double average = Arrays.stream(numbers).average().getAsDouble();
This should do the trick.
Arrays.stream(c).sum()/c.length is integer since both arguments are integer.
So you are trying to format Integer as float.
You need explicitly cast one of arguments to float (or double) to get decimal result.
Something like
Arrays.stream(c).sum()/(double)c.length
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
I'm using float to display decimal numbers, but sometimes it doesn't display correct result.
For example, for 6.2/1000 the result is 0.0061999997.
I know why is this happening, but I wonder is there a way to display correct result, in this case, 0.0062?
EDIT:
How to round a number to n decimal places in Java does not answer to my question, so why did you marked my question as already been answered in other place?
Numbers I wrote are only example. In the app user can enter any number and divide / multiply number with any other number, so the result maybe won't have any decimal points, maybe it will have 4 decimals, maybe it will have 7 decimals,...
First, you need to understand that this isn't just a display issue - if you want to avoid displaying incorrect values, it helps to have the right values to start with.
You should use BigDecimal instead of float. That stores the value as an integer scaled by a factor of 10exp rather than the 2exp used by double and float.
If the BigDecimal.toString doesn't format the result the way you want, use DecimalFormat to perform the formatting instead.
Format the decimal places use this:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(decimalPlace);
String formatedValue = df.format(value);
Hope this will resolve your query.
This question already has answers here:
How to nicely format floating numbers to string without unnecessary decimal 0's
(29 answers)
Closed 9 years ago.
I want to limit my numbers to 7 significant figures (I believe this is known as significant digits in American English) with a maximum of 5 decimal places but I am ensure on how to do this.
I am currently using %-7.5f but this always prints 5 decimal places, even if those places aren't significant.
I.e. 3.75 becomes 3.75000
Here's some examples to try and further clarify what I am after:
3097.0 -> 3097
10.39596 -> 10.396
79.6103426 -> 79.61034
I.e. No leading or trailing 0s, 7 significant figures and at most 5 decimal places.
I'm trying to do this as I am working on upgrading an old program written in QBasic and this is how it formats it's floating point numbers when they are displayed. I want my Java code to output the numbers this way simply to make it easier to compare the results.
You can use DecimalFormat for this
double value1 = 10.39596;
double value2 = 79.6103426;
DecimalFormat df = new DecimalFormat("#.#####");
System.out.print(df.format(value1));
System.out.print(df.format(value2));
I suggest to use DecimalFormat for this purpose
new DecimalFormat("#.#####").format(d)
this pattern limits fractional part to max 5 digits
What about
DecimalFormat format = new DecimalFormat("#.#####");
System.out.println(format.format(79.6103426));
This question already has answers here:
how to convert double to 2 number after the dot? [duplicate]
(6 answers)
Closed 9 years ago.
How to get the double value that is only two digit after decimal point.
for example
if
i=348842.
double i2=i/60000;
tv.setText(String.valueOf(i2));
this code generating 5.81403333.
But I want only 5.81.
So what shoud I do?
Use DecimalFormat.
DecimalFormat is a concrete subclass of NumberFormat that formats
decimal numbers. It has a variety of features designed to make it
possible to parse and format numbers in any locale, including support
for Western, Arabic, and Indic digits. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Code snippet -
double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));
Output -
5.81
How about String.format("%.2f", i2)?
Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
Many other answers only do formatting. This approach will return value instead of only print format.
double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);
I think the best and simplest solution is (KISS):
double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;
i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##");
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));
First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.
And other aspect is providing proper result. So you want to truncate the number or round it.
So before you start you should ask your self, am i interested on the value or not.
To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.