How to do intelligent decimal cut off in Java? - java

I want to implement or use some library for an intelligent decimal cut off.
I mean that I would like to get: from 3.456432 -> 3.4, from 0.0000023232432 -> 0.000002 and from 0.000000000001 -> 0.0 (or something like that). I need this feature for a convinient user GUI.
Thereby I need to reduce number of digits that are not equal to zero. I need to keep 1-3 most significant digits and other set to zero.

Have you taken a look at the DecimalFormat API?
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.

If it is of any help, you can use the following method to round a double to a specified number of significant digits. There are however no functionality in the standard API to output the result in a reasonable manner:
private static double round(double v, int sigDigits) {
double f = Math.pow(10, Math.ceil(Math.log10(Math.abs(v))) - sigDigits);
return Math.round(v/f)*f;
}

Since Java 5, java.util has a Formatter class which can do what you need.

Related

How do I comma separate zero padded String.format doubles in java?

I am trying to use String.format for get comma separated, zero padded doubles.
I am using:
"%0,9.2f", unitPrice
Unit price is a double. When unitPrice is, for example, 44.99 I get 000044.99 when I want 00,044.99. If unit price is 4499 instead I get 04,499.00 as wanted.
You could use a DecimalFormat (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) like
DecimalFormat df = new DecimalFormat("00,000.00");
System.out.println(df.format(44.99));
System.out.println(df.format(4499));
Output is (as requested)
00,044.99
04,499.00
This is only possible for values equal or larger than 1000. Checked the source code of Java 8 and the zero padding is done after inserting group separators.
You have to write your own format like the answer from #Elliot Frisch.
Note that his answer is Locale dependent, but you can force the comma , by providing a localized instance of DecimalFormatSymbols.
new DecimalFormat("00,000.00", DecimalFormatSymbols.getInstance(Locale.US))

Java and decimals E numbers

Java comes up with numbers like 9.870699812169277E-4
How should I interpret it? Is there a way to parse it in Java and display without that E?
You can use NumberFormat.
Code
// you can format to any output you want
NumberFormat formatter = new DecimalFormat("0.00000000000");
String string = formatter.format(9.870699812169277E-4);
System.out.println(string);
Result
0.00098706998
Related
Java: Format double with decimals and
Format numbers in java
I don't know of any language which doesn't support this notation (except perhaps machine code) Even most calculators support it.
I suspect the languages you have used before support this notation, however it just wasn't used.
9.870699812169277E-4 is the same 9.870699812169277 * 10-4 or 0.0009870699812169277
For your interest there is a P notation e.g. 0x1.fffffffffffffP+1023 which is a hex notation for a double.

Four questions - Calculator Application - Android Java

Hey all, I am a total newbie developing an android application, I've been reading 'Sams Teach Yourself Java in 24 hours' and it's a great book. But I have been stuck on a bit where I get the value of a decimal number only editTexts and use java maths to work out my end value.
Is there a way to have an editText input straight to a float or double variable rather than to a string and then from a string to a double?
Are there any real issues with converting between a string and a double or float or will the values remain the same and not be polluted.
Differences / pros and cons of using a doble as opposed to a float.
Best way to input a fraction value from the user?
Thanks for any help. Have a good day.
No, you can't.
Yes. If your string is, say, an ID and reads like "0029482", after you turn it into an integer it will read "29482" and probably will be invalid. Strings can be longer than doubles or floats, and if you have a value like "0.12345678901234567890123456789" in a string, you will lose a lot of precision by converting that to a double.
Doubles use double the number of bits (hence the name), and can therefore hold more precision.
Accept the denominator and numerator integers, and store them in a custom class.
No. You could write your own subclass that makes it seem like that is what's happening, but at some point somewhere in the chain you have to do a conversion from character/text data to numerical data.
Yes. Primitive floating-point types use IEEE-754 to encode decimal numbers in binary. The encoding provides very good precision, but it is not exact/cannot exactly represent many possible numbers. So if you parse from a string to a primitive floating-point type, and then back to string again, you may get something that is different from your input string.
A double uses twice as many bits to encode the number as a float, and thus is able to maintain a greater degree of precision. It will not, however, remove the issues discussed in #2. If you want to remove those issues, consider using something like BigDecimal to represent your numbers instead of primitive types like float or double.
Read the whole thing as a string, split() it on the '/' character, and then store each part as an integer (or BigInteger). If you need to display it as a decimal, use BigDecimal to perform the division.
I'd just like to add that if you are looking for an alternative to double or float that doesn't entail loss of precision when converting between strings and numeric form, look at these:
The standard java.math.BigDecimal class represents an arbitrary precision scaled number; i.e. an arbitrary precision integer multiplied (scaled) by a fixed integer power of 10.
The Apache dfp package contains implementations of decimal-based floating numbers.
However, I'd steer clear of both of this topic for now, and implement using float or double. (I take it that your real aim is to learn how to write Java, not to build the world's greatest calculator app.)

Displaying doubles to a certain precision in java

I am currently writing a calculator application. I know that a double is not the best choice for good math. Most of the functions in the application have great precision but the ones that don't get super ugly results. My solution is to show users only 12 decimals of precision. I chose 12 because my lowest precision comes from my numerical derive function.
The issue I am having is that if I multiply it by a scaler then round then divide by the scaler the precision will most likely be thrown out of whack. If I use DecimalFormat there is no way to show only 12 and have the E for scientific notation show up correctly, but not be there if it doesn’t need to be.
for example I want
1.23456789111213 to be 1.234567891112
but never
1.234567891112E0
but I also want
1.23456789111213E23 to be 1.234567891112E23
So basically I want to format the string of a number to 12 decimals places, preserving scientific notation, but not being scientific when it shouldn't
Use String.format("%.12G", doubleVariable);
That is how you use format() to display values in scientific notation, but without the scientific notation if not needed. The one caveat is that you end up with a '+' after the 'E', so yours would end up like 1.234567891112E+23
String.format("%.12d", doubleVariable);
Should give you what you are looking for in your first matter. I'm sorry but I don't know how to define when your E-notification is showed.
You'll be interested in BigDecimal, for example:
BigDecimal number = new BigDecimal("1.23456789111213");
number = number.setScale(12, RoundingMode.HALF_UP);
System.out.println(number);
Choose appropriate to you RoundingMode.

scientific notation abstraction in java

Is there a java class abstraction to denote scientific numbers (e.g. the number, 10 power modulus), so that I can do simple operations like multiplication or division on top of them.
Note: Looking for something similar to Fraction here.
As Emil said, BigDecimal helps you. It doesn't have a constructor that lets you enter a double mantissa and an int exponent. You could extend the class to make a new constructor, or, you could define a DecimalFormat. I think that the class DecimalFormat will do some of what you want. It allows you how to define how a number 'looks'. You need to define the format using a String, the tutorial is
http://download.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
You would have to define the format of scientific numbers, call yourDecimalFormat.parse(yourStringtoBecomeScientificNumber) which will give you a Number, then cast it as a BigDecimal to do arithmetic on it.
Also note that this should allow you to force a certain number of significant figures or digits to left of decimal point.
I didn't get your example.If you need a different type of number representation then you can do so by extending abstract class Number.Also have a look at BigDecimals .I think this is what you are looking for.
You could write the number as number+e+exponent, e.g.:
1e2 instead of 100.
Multiplication and Division should work for it.

Categories