How to keep n decimal places in Java - java

Hi All it might be a trivial question but as for now I could not find any solution.So asking for your help!
What I am trying to get is a specific encoding table that looks like this:
0.000
0.100
0.200
I need to keep track of zeroes as I will use them to reconstruct a part of an specific array. Original loop that was creating those numbers is:
for(int k=0;k<m_0;k++){
for(int l=0;l<m_1;l++){
for(int a=0;a<a1;a++){
Y[x-1]=0.1*k+0.01*l+0.001*a;
x++;
}
}
}
Problem! I could not fix zeros after decimal place and rather then getting table described above I am getting following:
0.0
0.1
0.2
As a solution I have tried to use BigDecimal and DecimalFormat but no success. Any suggestions?
UPD Few words what I am trying to do. I am encoding specific array to array and back index correspondence. For example 0.100 will be decomposed into 1 and 0 and 0 and used as array index labeling like:
Array1[Method(1,0,0,Y(i)][Method(1,0,0,Y(i))]=Array2[1][0][0]
So that I need an output suitable for assigning array index and string will not do the deal.

The DecimalFormat class is the correct place to look. You just need the correct format.
DecimalFormat df = new DecimalFormat("0.000");
System.out.println(df.format(0.1));
Output:
0.100

As an alternative to the DecimalFormat class, I would like to propose the following (which I use quite regularly):
Step 1: Create a function that allows me to specify the number of units to keep. Here is a copy of this function.
public static String format(Number n) {
NumberFormat format = DecimalFormat.getInstance();
format.setRoundingMode(RoundingMode.FLOOR);
format.setMinimumFractionDigits(0);
format.setMaximumFractionDigits(2);
return format.format(n);
}
Step 2: Call the function whenever you have any output to format. Below is a simple example using this function to set the appropriate decimal place length:
System.out.println("Based on this, the wind chill index was calculated to be " + format(chill));
Note that you could simply change the line:
format.setMaximumFractionDigits(2);
to
format.setMaximumFractionDigits(n);
depending on your desired decimal length.

When you are printing the numbers, you can use this:
System.out.format("%.3f", yourDecimalNumber);

Related

Aproximation of log(10^k)

I am trying to find the result of log(10^k) , where k is big number like 10000. For example :
BigDecimal first = BigDecimal.TEN.pow(10000);
double result = Math.log(first.doubleValue());
However "result" becomes Infinity , however on wolphram approximates it to 23025.85.Any suggestion how to find the result? As a result the number with the first two digits after the decimal point are enough for me.
Use the fact that
log(10^k) = k*log(10)
So:
System.out.println(10000 * Math.log(10));
Prints:
23025.850929940458
The problem you are likely having, is that Wolphram is able to either hold the powered value or it is doing the log operation first.
When running this like your example, you will have an extremely large number that goes past the maximum value for a BigDecimal, which should result in an error or an "infinity", because it overflows the capability of the data type, I would suggest doing the operation the other way arround, perhaphs process the log first on a base 1 value for example and only then multiply it by whatever powered number you are tying to use.
See, there is a simple property of logarithms that you can use:
log(x^y) = y*log(x)
So what you can do is:
double y = y*log(x);
System.out.println(Math.round(y));
Hope this helps!

Translate Hexadecimal transformation from Oracle SQL into Java code

In searching for an answer, I used the solution provided in the following link : How to format a Java string with leading zero?
I have the following code that needs to be translated into java:
TRIM(TO_CHAR(123,'000X'))
From what I can tell, it translates the number into hexa and adds some leading zeros.
However, if I give a big value, I get ##### as answer, e.g. for the following code:
TRIM(TO_CHAR(999999,'000X'))
In Java, my current solution is the following:
String numberAsHex = Integer.toHexString(123);
System.out.println(("0000" + numberAsHex).substring(numberAsHex.length()));
It works fine for small numbers, but for big ones, like 999999 it outputs 423f. So it does the transformation, resulting the value f423f and then it cuts a part off. So I am nowhere near the value from Oracle
Any suggestion as to how to do this? Or why are ##### displayed in the Oracle case?
Instead of Integer.toHexString I would recommend using String.format because of its greater flexibility.
int number = ...;
String numberAsHex = String.format("%06x", number);
The 06 means you get 6 digits with leading zeros, x means you get lowercase hexadecimal.
Examples:
for number = 123 you get numberAsHex = "00007b"
for number = 999999you get numberAsHex = "0f423f"

Having issue with a very simple java program, not displaying proper result

here is my code that isn't working:
Scanner hello = new Scanner (System.in);
double a = 10;
double c;
System.out.print("Enter the value: ");
c = hello.nextDouble();
double f = a + c;
System.out.printf("The sum of 10 plus user entry is : ", a+c);
No syntax error whatsoever, no error displayed, this is the result :
Enter the value: 100
The sum of 10 plus user entry is :
So there is no result in the second line,,, for the command ( a+c ) as in program. But if i use a ' %.2f ' before ( a+c ) command, it works fine,,
like :
System.out.printf("The sum of 10 plus user entry is : %.2f", a+c);
I tried to search about the '%.2f' but got to know it is used just to ascertain that the following number is to be displayed as a number with two decimal places. (kinda round off thing, i guess)..
I'm totally a rookie at Java. Started studying it at college right now. Was just curious to know about this concept and reason behind why this program worked only with the '%.2f' typed in it, and not without it, although it showed no error. Will be great if someone can answer it. thanks :-)
Java's System.out.printf() method doesn't append information; it substitutes it. The '%.2f' means: "Replace this with the next argument, and convert it to a floating-point number 2 places precise." Removing the '%.2f' would mean that a+c would have nowhere to go, and printf() would discard it.
Since Java's System.out.printf() method is actually based on the printf() from C/C++, you might want to check out this guide.
You are using the wrong function.
You should be using
System.out.println(myString)
Or
System.out.print(myString)
You would format your code as
System.out.println(myExplinationString + a+c)
System.out is an instance of java.io.PrintStream class that is provided as a static field of the System class. printf(String format, Object... args) is one of the methods of the PrintStream class, check this Oracle tutorial on formatting numbers. In brief, the first argument is a format string that may contain plain text and format specifiers, e.g. %.2f, that are applied to the next argument(s). All format specifiers are explained in the description of the java.util.Formatter class. Note, that double value is autoboxed to Double.

Retain formatting of a Double value - Java

I am using Poi to create Excel workbooks in Java. My raw data comes in as a string. I need to format the data to enter two decimal places into the cell where the number is being written. I use Double.parseDouble() to convert the string to numeric and then use DecimalFormat to format the numeric as a string. Another call to Double.parseDouble() to return the value to numeric (the cell where it is going is formatted numeric, so I can't use the string value) and I should be good. Problem is, that second call to Double.parseDouble() truncates any trailing zeroes off from the right of the decimal point. Anybody have an idea as to how I can coerce this value to read as, say, 1.50 rather than 1.5?
I always want two decimals.
Solution: Always apply specific decimal format pattern.
Sample code snippet:
//java.text.DecimalFormat df = new java.text.DecimalFormat( "###0.00" );
java.text.DecimalFormat df = new java.text.DecimalFormat();
df.applyPattern( "###0.00" ); // always two decimals
double dbl = 1.50d ;
// prints: dbl = 1.5
System.out.println( "dbl = " + dbl );
// prints: df.format( 1.5 ) = 1.50
System.out.println ( "df.format( " + dbl + " ) = " + df.format( dbl ) );
UPDATE:
OK, from your posting, I understand that you are trying to fill the numeric formatted cell only to print or show up with two decimal positions. You know by default all numeric fields are interpreted omitting trailing zeros. To achieve your requirement, you may require to use CellFormat and/or DataFormatter on your contextual Cell object, but when said Format, it is a String again.
I didn't try the following code but may help you.
DataFormatter dataFormatter = new DataFormatter();
dataFormatter.setDefaultNumberFormat( instanceOfDesiredDecimalFormat );
// or
// dataFormatter.setExcelStyleRoundingMode( instanceOfDesiredDecimalFormat );
// apply this format on the cell you want
dataFormatter.formatCellValue( instanceOfNumericCellInContext );
You are actually doing nothing in most part of the code you described. You might as well just return Double.parseDouble(inputString). Doubles are stored in binary format and the leadin/trailing zeros make no sense. Perhaps the BigDecimal class is something for you.
It appears we are at an impasse. As Mario pointed out, doubles are managed as binary and there is no way to format the binary as a double, except to convert it to a string with DecimalFormat, which is no longer a double. I explained this to my boss and he's ok with the solution of taking the raw double, so I'm closing this issue. Thanks to all for your help and support.
regards,
Mike

Formatting a Double into the correct format

Having problem getting a Longitude/Latitude into the correct format for an api we don't have access to.
We need to convert this to a string and at the moment we have: 4.30044549E7
as the raw form but we need to convert it into 4.30044549 or similar (without Scientific Notation)
If we use
NumberFormat f = new DecimalFormat("#.#######");
f.format(4.30044549E7);
we get: 43004454.9
if we use
Double.toString(4.30044549E7);
we get: "4.30044549E7"
if we try to convert to an int we also get 43004454.9
Can anyone help? I can't find an acceptable solution to get rid of scientific notation on the number
If you really asked what I think you did, you could simply divide the number by 10 until you reach the format you wanted.
double value = 4.30044549E7;
while(value > 10 || value < -10){
value /= 10;
}
System.out.println(String.format("%.8f", value)); //4.30044549
Have you tried format?
String.format("%.10f",doubleValue);
It will format your number with 10 digits after dot.
1e-5 -> 0.000010000
1e5 -> 100000.0000000000
you never can "format" 4.30044549E7 into 4.30044549 because they are not the same.
4.30044549E7 is in fact 43004454.9 so wanting a formatter to display that double as 4.30044549 is an odd question

Categories

Resources