how to set number format to cells using jexcel api - java

I am writing a excel sheet with various floating values . It is absolutely necessary that i do not lose any decimal point when doing this. I am using this code:
number = new Number(1, rowno2,biashidden[i]);
sheet.addCell(number);
When i do this, the default format is only up to 3 decimal places. I can see the values written correctly in the excel sheet, but when do System.out.println , i see only values upto 3 decimal places. I do not know upto how many places the values will be, it may be 1.0 or it may 1.0000045667 ( thus i cannot specify a maximum limit using Numberformat too).
What should i do?
Thanks in advance

This is the code for my problem .
WritableCellFormat wcf1=new WritableCellFormat(new jxl.write.NumberFormat("#.###############"));
wcf1.setShrinkToFit(true);
try
{
for(int i=0;i<=numberOfNeurons[0];i++)
{
for(int j=0;j<numberOfNeurons[1];j++)
{
number = new Number(0,rowno1,wtofnetwork[i][j],wcf1);
sheet.addCell(number);
rowno1++;
}
}
For some reason, we cannot specify the number of decimal places dynamically. so i gave enough decimal places so that no digit is lost. It is a crude way of doing it , but it achieves the purpose.

Related

Numbers length of JFormattedTextField mask Java

I'm developing an desktop application with java, right now I'm at the point of registering person data. One of the fields of the person form is "DocumentTextField" which holds the Identification Document and Number, that's why I tried to use a JFormattedTextField mask, to help user with the format to this field.
Basically, I just used the AbstracFormatterFactory to create the mask:
Mask = UU - ########## to get something like (PP-0123456789)
It does work perfecly on the fly, the user just type "pp0123456789" and the mask become this to "PP-0123456789" the point is the numbers length, as you can see on my mask, i declare 10 numbers (##########) but in fact, It could be lower than 10 numbers or even Higher. It does only work with 10 numbers, if user type lower than 10 numbers, the JFormattedTextField resset to empty, the same thing happen if user type more than 10 numbers.
is there any way to declare the range (numbers length) of this? some document are just 5 numbers (PP-01234).
Thank you so much in advance by reading this and trying to help.
I assume you're using Java 8 for your development. Are you seeing any kind of ParseException?
As per the documentation of the component: https://docs.oracle.com/javase/8/docs/api/javax/swing/text/MaskFormatter.html
When initially formatting a value if the length of the string is less than the length of the mask, two things can happen. Either the placeholder string will be used, or the placeholder character will be used. Precedence is given to the placeholder string.
According to the example:
MaskFormatter formatter = new MaskFormatter("###-####");
formatter.setPlaceholderCharacter('_');
setPlaceHolderCharacter method can help you with your problem.

Java: Limiting decimals from a double in output without e.g. %5.2d

I'm very (read: extremely) new to java and was going to make a table with 5 columns print out for an assignement.
The two first columns are strings, third one an int, fourth a double and fifth an int. It is three rows in total that are affected by this.
I formatted it with printf and:
System.out.printf(Locale.ENGLISH, "%s%10s%14d%20.2f%12d\n", stringOne,
stringTwo, firstInt, stupidDouble, secondInt);
and
"%s\t%s\t\t%d\t\t%2.4f\t\t%d\n" (with the format and stuff above as well ofc).
But the teacher didn't want me to "hard code" the layout since it's part of learning special commands (like \t) and thus wanted me to change it and adress it in the variable itself instead.
I've been trying everything I can think of but can't get it to skip the last decimals, which are unneccesary 0's.
I wish I could've just used the numbers as a string instead, but I need it to calculate the last int with:
static int lastInt = (int) Math.round ( stupidDouble - firstInt )
What I suspect that my teacher is looking for me to do is tabs all the way like:
"%s\t%s\t\t%d\t\t%f\t\t%d\n"
But I need to double to be e.g. 1.2345 instead of 1.234500.
If it makes any difference, it's 3 different doubles (3 different rows in the table); one with 2 decimals, one with 4 and one with 5.
It would more or less save my weekend if someone could help me with this. The simplest possible solution would be much appreciated. <3

How to keep n decimal places in 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);

How to format numbers on Android

i am learning to program mobile aplications on Android. My first app is a unit converter. Everithing is working for now, but i have a question about formating numbers. I hava this code to get text from buttons and to convert the appropriet output:
if (bPrevodZ.getText() == "milimeter"){
if (bPrevodDo.getText()=="kilometer"){
String PomocnaPremenna = jednotkaZ.getText().toString();
double cisloNaPrevod = Double.parseDouble(PomocnaPremenna);
cisloNaPrevod = cisloNaPrevod*0.0000001;
vysledok.setText(Double.toString(cisloNaPrevod));
}
The final result is "cisloNaPrevod", but i have problems to show a good format of that number. For example:
12345 mm = 0,0012345 km this is good right ? :)
but if i convert:
563287 mm = 0.05632869999999995 this is bad :) i need it to show 0.0563287
Thx for any help
Use String.format:
String.format("%.6f", cisloNaPrevod);
If you want your number to always have 6 significant figures, use
vysledok.setText(String.format("%.6g", cisloNaPrevod));
giving the result 0.0563287.
If you want to round to 6 numbers after the decimal place, use
vysledok.setText(String.format("%.6f", cisloNaPrevod));
giving the result 0.056329.
Here's some good resources that cover number formatting:
Floating-point cheat sheet for Java
java.util.Formatter
If it's something you're going to do often, perhaps you should use DecimalFormat.
DecimalFormat df = new DecimalFormat("#.#######");
Then call:
df.format(someDoubleValue);

help regarding rounding off numbers

float per = (num / (float)totbrwdbksint) * 100;
i m getting the value of per as say 29.475342 . i want it to round off upto two decimal places only.like 29.48 .how to achieve this?
You should do this as part of the formatting - the floating point number itself doesn't have any concept of "two decimal places".
For example, you can use a DecimalFormat with a pattern of "#0.00":
import java.text.*;
public class Test
{
public static void main(String[] args)
{
float y = 12.34567f;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(y));
}
}
As Jon implies, format for display. The most succinct way to do this is probably using the String class.
float f = 70.9999999f;
String toTwoDecPlaces = String.format("%.2f", f);
This will result in the string "71.00"
If you need to control how rounding is done you should check BigDecimal ist has several rounding modes. http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html
You need to be careful here, this answer is not related to java, it relates to all aspects of decimals in many programming languages hence it is generic. The danger lies with rounding numbers, is this, and it has happened in my experience and know that it can be tricky to deal with:
Supposing you are dealing with prices on items, the pricing you get from a retail supplier may be different to the price the computer tells you, sure it is marginally small, but it could add up to big money.
Adding a sales tax on a price can either be positive or negative, it can impact the operating margin of the profit/loss balance sheets...
If you are in this kind of arena of development, then my advice is not to adjust by rounding up/down...it may not show up on small sales of the items, but it could show up elsewhere...an accountant would spot it...Best thing to do is to simply, truncate it,
e.g. 29.475342 -> 29.47 and leave it at that, why?, the .005 can add up to big profit/loss.
In conjunction to what is discussed here...electronic tills and registers use their own variety of handling this scenario, instead of dealing with XX.XXXXXXXXXX (like computers, which has 27/28 decimal places), it deals with XX.XX.
Its something to keep in mind...
Hope this helps,
Best regards,
Tom.
you can use the formatted print method System.out.printf to do the formatted printing if that's what you need

Categories

Resources