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

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.

Related

Format double as 4+ digit String

I have a double which contains values such as:
19.52
5.1
6.13
101.5
It will not contain more than 2 fractional digits. That is being checked for. If there are more than 2, the rest can be ignored.
I'd like to convert it to a String which has 4+ digits, like this:
"1952"
"0510"
"0613"
"10150"
How can I do that?
I'm using someone's API and the last 2 digits are specified as being always for the first 2 digits of the fractional part, that's why I need to do this.
You can multiply your number by 100 to remove the decimal point (because you only have 2 decimal digits), and then use the format 0000 to format it:
DecimalFormat df = new DecimalFormat("0000");
System.out.println(df.format(x * 100));
where x is your double.

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.

Format decimal values with String in 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);

Remove trailing numbers

Why I get trailing so many numbers when I run below code?
BigDecimal lat = new BigDecimal(0.0077);
System.out.println(lat);
output >>
0.00770000000000000024702462297909733024425804615020751953125
I want to print exactly what I entered. How can I do this?
Most finite decimal fractions cannot be exactly represented by floating-point, so that is the approximation you get when you create the floating-point literal 0.0077.
To avoid the problem, use the constructor BigDecimal(String val) instead:
BigDecimal lat = new BigDecimal("0.0077");
As #TimB points out, if you already have a double value, you can also use:
BigDecimal lat = BigDecimal.valueOf(doubleVal);
Also, here is the mandatory reference to What Every Computer Scientist Should Know About Floating-Point Arithmetic.
When you have a number like 0.077 this cannot be exactly represented and in fact you get a number which is almost this, but with a small error. When you print this number as a string, the code to do this "knows" to discard the small error and you see the number you expect.
BigDecimal tries to give you a faithful representation and it is doing what it should even if this is surprising. What you want to use is the following method
BigDecimal bd = BigDecimal.valueOf(0.077);
In this case the BigDecimal takes the value as it would be printed, instead of the true value represented.
why is it so long?
To accurately represent a 53-bit fraction (double has a 53-bit mantissa) you need 53 decimal digits. e.g. every time you multiple by 10 to get another digit, you multiple 2 (and 5) which makes the lower bit 0 and eventually you guarentee to have all 0 bits and no more digits.
Try this:
System.out.println(String.format("%.4f",lat));
where 4 in %.4f specified how many decimal places you want to display
Note that this will only format your output display. the actual value of lat however still 0.00770000000000000024702462297909733024425804615020751953125
You can also use NumberFormat and specify the fraction digits setMinimumFractionDigits(4)
BigDecimal lat = new BigDecimal(0.0077);
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(4);
System.out.println(nf.format(lat));
BigDecimal lat = new BigDecimal(0.0077);
lat=lat.setScale(4,RoundingMode.HALF_EVEN);
System.out.println(lat);

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)).

Categories