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
Related
I am suprise to see the below program please advise how it is behaving like this as i aam very much concerened with poitn to precison after decimal point , below is the progrmam
double fixedRate = 0.997500000000; //**output --->0.9975
// BigDecimal fixedRate = new BigDecimal("0.997500000000");
double fixedRate1 = 0.1234567890123456789;
System.out.println(fixedRate);
System.out.println(fixedRate1);
and the output is
0.9975
0.12345678901234568
now please advise for the first the ouput is 0.9975 but late on for next it is not truncating after decimal points but why for first then.
The precision is not lost. It is just not printed because you do not need more digits to distinguish the printed value from any other double value.
If you do want to force a certain number of fractional digits, take a look at System.out.printf() or String.format().
See https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html for more details and possible formats.
The result may look like this:
System.out.printf("%.19f%n",fixedRate);
System.out.printf("%.19f%n", fixedRate1);
This is a printing problem.Please use this format to print your values and tell me the result:
double fixedRate = 0.997500000000;
double fixedRate1 = 0.1234567890123456789;
System.out.println(String.format("%.19f", fixedRate ));
System.out.println(String.format("%.19f", fixedRate1 ));
Good Luck !
According to your question
for the first the ouput is 0.9975 but late on for next it is not
truncating after decimal points but why for first then
Since double is numeric datatype and hence cannot hold the leading and trailing zeros.
A double doesn't care about formatting - it's about storage only. When you print it, it is converted to a String (using Double's static toString method).
In simple terms the value 0.9975 is not different from 0.997500000000or it is same as 0.997500000000 as zeros after a number will not have any value.
But consider if you had value like this 0.9975000000001 then all the numbers will be printed. Check it here.
If you want to format the value then you can see this question : How to properly display a price up to two decimals (cents) including trailing zeros in Java?
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 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.
float a= (float) 1846.4;
NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
float b = Float.parseFloat( df.format(a));
What would be the best way to set decimal places for a float (I just want to set 2 decimal places of a float value which can be 2013.43452 or 2392.2) ? Now I am getting exception like Exception in thread "main" java.lang.NumberFormatException: For input string: "1,846.40".
I think the direct problem causing the NFE is the thousand separators in the string, not the number of decimal places. You have both a ',' and a '.' in the string, and parseFloat doesn't like that.
Note, however, that you can't fix the number of decimal places in a float value - it is entirely a formatting issue. Specifically, trailing 0's have no significance in floating point values, thus will not be shown by default. You need to format the value according to your wishes at the point of output (when converting it into a displayable String e.g. by using DecimalFormat as you did above).
To get your formatting + parsing to work, just use df again:
float b = df.parse( df.format(a));
However, I still don't see any sense in that. You can't define the number of decimal places in a floating point number. 1846.40 is the same as 1846.4 or 1846.400, the trailing zeros are totally irrelevant.
Those digits come into play when you have output, e.g. writing the number to a string. But there are other facilities to do that, e.g. a string format pattern.
If you need to restrict the number of fraction digits internally use BigDecimal where you can set the scale and thus define the number of fraction digits it represents.
Sounds like you simply want to round to two decimal places.
Number format and mucking around with strings isn't where you want to go.
Try this:
float b = Math.round(a * 100)/100.0f;
What would be the best way to set decimal places for a float
There isn't one. Floats don't have decimal places. They have binary places.
If you want decimal places you have to use a decimal radix, either a BigDecimal or the result of DecimalFormat.format().
How to read a double value from a String with a certain precision (say 4) assuming the string contains something like "10.1234" using this api
If you want decimal precision, double is the wrong target type, as it is a binary format that cannot accurately represent most round decimal fractions. That double value will actually be rounded to something like 10.123399999999999999976
Instead, use BigDecimal all the way, or forget about runding while you read and manipulate the data, and round it only when you print the result.
Read The Floating-Point Guide for more information.
System.out.println(new Double(new BigDecimal("10.123456789").
setScale(4, BigDecimal.ROUND_DOWN). // choose precision and specify rounding policy
doubleValue()
));
>> run:
10.1234
I assume that your String also contains letters.
You can parse the number out of the String first:
String numberString = ...
int precision = ...
int index = numberString.indexOf(".");
numberString = numberString.substring(0, index+precision+1); // Maybe without "+1"
Double number = Double.valueOf(numberString);
You can use regular expression to truncate the String to at most 4 digits following the decimal point, then use Double.valueOf.
String[] tests = {
"12",
"12.",
"12.3",
"12.34",
"12.345",
"12.3456",
"12.34567",
"-123.45678",
"1.23456.789.0",
};
for (String test : tests) {
String truncated = test.replaceAll("(\\.\\d{4}).*", "$1");
System.out.printf("%15s %15s %15s%n",
test, truncated, Double.valueOf(truncated)
);
}
This prints:
12 12 12.0
12. 12. 12.0
12.3 12.3 12.3
12.34 12.34 12.34
12.345 12.345 12.345
12.3456 12.3456 12.3456
12.34567 12.3456 12.3456
-123.45678 -123.4567 -123.4567
1.23456.789.0 1.2345 1.2345
How the regex works
It captures a literal ., followed by up to four digits \d{4}, into \1. It also matches everything else that may follow .*, and replaces the whole thing with $1 (backreference to what \1 captured).
The advantage of this over, say, a simple indexOf approach is that it works even when there aren't 4 digits, or even when there isn't even a decimal point at all, without requiring special treatment.
See also
regular-expressions.info
Java Tutorials/Regular expressions
You can do something like
Math.round(number*100)/100
to get the precision, but this will probably not do what you want due to the internal representation of floats and doubles.
If you really need to work with a fixed number of digits after the decimal point consider using BigDecimal.
For formatting output you can use the C-like printf functionality as decribed in this article. It is not pretty but practical.