format datacell to comma(?) - java

Hi i want to edit these cells to have a comma instead of a decimal point.
they are exported from my database to a excel sheet, but instead of the decimal point i want a comma
( , )
can anyone help please?
int r = 1;
while (rs.next() )
{
String vpid = rs.getString("VP_ID");
String vtb = rs.getString("partner");
String bs = rs.getString("Bonus");
String bo = rs.getString("Bonus2");
row = sheet.createRow(r++);
row.createCell(0).setCellValue(vpid);
row.createCell(1).setCellValue(vtb);
row.createCell(2).setCellValue(bs);
row.createCell(3).setCellValue(bo);

That question seems to be a good example for a XY problem.
One gets numbers as text values from a database and writes them into a Excel sheet:
...
String bs = rs.getString("Bonus");
String bo = rs.getString("Bonus2");
...
row.createCell(2).setCellValue(bs);
row.createCell(3).setCellValue(bo);
...
Let bs be "123.45" and bo be "67.89", then the Excel cells will contain the texts "123.45" and "67.89" after that instead of the numbers 123.45 and 67.89.
Now one looks at that and uses Excel in a locale which has set comma as the decimal separator instead of dot. The misinterpretation now is, that Excel's interpretation of the numbers as text is because the wrong decimal separator. So one asks how to change the decimal separator.
But the real reason for Excel's interpretation of the numbers as text is because the code really sets text values instead of numbers. The decimal separator is not a format in Excel but only determined by used locale or by a extended application property. If numbers shall be cell contents then the cell value needs to be set using Cell.setCellValue(double value) and not using Cell.setCellValue(java.lang.String value). Using what decimal separator the number then gets showed in the sheet depends on used locale or the extended application property for decimal separator.
So the correct solution is to set the cell values as doubles. Either by doing:
...
row.createCell(2).setCellValue(Double.valueOf(bs));
row.createCell(3).setCellValue(Double.valueOf(bo));
...
But better would be to save the values correctly as numbers in the database and to retrieve them from the database like so:
...
double bs = rs.getDouble("Bonus");
double bo = rs.getDouble("Bonus2");
...
row.createCell(2).setCellValue(bs);
row.createCell(3).setCellValue(bo);
...

Related

Convert in reverse ascii to whole decimal in Java

Hi all and thank you for the help in advance.
I have scoured the webs and have not really turned up with anything concrete as to my initial question.
I have a program I am developing in JAVA thats primary purpose is to read a .DAT file and extract certain values from it and then calculate an output based on the extracted values which it then writes back to the file.
The file is made up of records that are all the same length and format and thus it should be fairly straightforward to access, currently I am using a loop and and an if statement to find the first occurrence of a record and then through user input determine the length of each record to then loop through each record.
HOWEVER! The first record of this file is a blank (Or so I thought). As it turns out this first record is the key to the rest of the file in that the first few chars are ascii and reference the record length and the number of records contained within the file respectively.
below are a list of the ascii values themselves as found in the files (Disregard the " " the ascii is contained within them)
"#¼ ä "
"#g â "
"ÇG # "
"lj ‰ "
"Çò È "
"=¼ "
A friend of mine who many years ago use to code in Basic recons the first 3 chars refer to the record length and the following 9 refer to the number of records.
Basically what I am needing to do is convert this initial string of ascii chars to two decimals in order to work out the length of each record and the number of records.
Any assistance will be greatly appreciated.
Edit...
Please find below the Basic code used to access the file in the past, perhaps this will help?
CLS
INPUT "Survey System Data File? : ", survey$
survey$ = "f:\apps\survey\" + survey$
reclen = 3004
OPEN survey$ + ".dat" FOR RANDOM AS 1 LEN = reclen
FIELD #1, 3 AS RL$, 9 AS n$
GET #1, 1
RL = CVI(RL$): n = CVI(n$)
PRINT "Record Length = "; RL
reclen = RL
PRINT "Number of Records = "; n
CLOSE #1
Basically what I am looking for is something similar but in java.
ASCII is a special way to translate a bit pattern in a byte to a character, and that gives each character a numerical value; for the letter 'A' is this 65.
In Java, you can get that numerical value by converting the char to an int (ok, this gives you the Unicode value, but as for the ASCII characters the Unicode value is the same as for ASCII, this does not matter).
But now you need to know how the length is calculated: do you have to add the values? Or multiply them? Or append them? Or multiply them with 128^p where p is the position, and add the result? And, in the latter case, is the first byte on position 0 or position 3?
Same for the number of records, of course.
Another possible interpretation of the data is that the bytes are BCD encoded numbers. In that case, each nibble (4bit set) represents a number from 0 to 9. In that case, you have to do some bit manipulation to extract the numbers and concatenate them, from left (highest) to right (lowest). At least you do not have to struggle with the sequence and further interpretation here …
But as BCD would require 8-bit, this would be not the right interpretation if the file really contains ASCII, as ASCII is 7-bit.

How to divide the value of a field in a tmap in TALEND

I'm just getting started with Talend and I would like to know how to divide a value from a CSV file and round it if possible?
Here's my job layout:
And here's how my tMap is configured:
I assume the "/r" is to add a new line? That won't actually work and will instead add a string literal "/r" to whatever other string you're adding it to. You also don't need to do that because Talend will automatically start a new line at the end of the row of data for your tFileOutputDelimited.
But more importantly, you're attempting to call the divide method on a string which obviously doesn't exist (how would it be defined?).
You need to first parse the string as a numeric type (such as float/double/Big Decimal) and then divide by another numeric type (your Var1 is defined as a string in your example, so will actually fail there too because a string must be contained in quotes).
So typically you would either define the schema column that you are dividing as a numeric type (as mentioned) or you'd attempt to parse the string into a float in the tMap/tJavaRow component.
If you have your prices defined as something like a double before your tMap/tJavaRow operation that divides then you can use:
row1.prix2 / Var.var1
Or to round it to two decimal places:
(double)Math.round((row1.prix2 / Var.var1) * 100) / 100
You can also use a tConvertType component to explicitly convert between types where available. Alternatively you could parse the string as a double using:
Double.parseDouble(row1.prix2)
And then proceed to use that as previously described.
In your case though (according to your comment on Gabriele's answer), there is a further issue in that Java (and most programming languages) expect numbers to be formatted with a . for the decimal point. You need to add a pre-processing step to be able to parse your string as a double.
As this question's answers show, there are a couple of options. You can use a regex processing step to change all of your commas in that field to periods or you can use a tJavaRow to set your locale to French as you parse the double like so:
NumberFormat format = NumberFormat.getInstance(Locale.FRENCH);
Number number = format.parse(input_row.prix2);
double d = number.doubleValue();
output_row.nom = input_row.nom;
output_row.code = input_row.code;
output_row.date = input_row.date;
output_row.ref = input_row.ref;
output_row.ean = input_row.ean;
output_row.quantitie = input_row.quantitie;
output_row.prix1 = input_row.prix1;
output_row.prix2 = d;
And make sure to import the relevant libraries in the Advanced Settings tab of the tJavaRow component:
import java.text.NumberFormat;
import java.util.Locale;
Your output schema for the tJavaRow should be the same as the input but with prix2 being a double rather than a string.
Since var1 is defined as String you cannot apply the divide method. Try something like this for your output prix2 calculus:
(Float.parseFloat(row1.prix2)/2200f) + "Vr"
or something like that (I cannot read the text in the screenshot very well, actually)

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

cleanly lining up output

I have a text file that contains data that was saved using the cvs encryption and I want to open it in java and display it lined up perfectly. I have come to the point of reading it from the text file but now I want it to be split at the commas and now I want to display it all perfectly aligned.
Last, First, car year, car model
barry, john, 1956, chevy impala
and I want it to display like this:
last First car year car model
barry john 1956 chevy impala
and I am just using the scanner class to get the data from the text file.
Determine the max lengths of the column values (including column headers), then create a format String and use that format string to build the aligned rows:
// some easy magic first
String[][] values = getCsvValues(file);
int[] maxLengths = determineMaxLengths(values);
// create formatstring, something like "%10s %5s %10s %n"
StringBuilder formatBuilder = new StringBuilder();
for (int maxLength:maxLengths)
formatBuilder.append("%").append(maxLength).append("s ");
formatBuilder.append("%n"); // newline
// output
for (String[] row:values)
System.out.printf(formatBuilder.toString, row);
depending on how certain you need to be that it all lines up, you might have to go through and find the longest string for each column, but I would use tabs: "\t". Two or three between columns usually works for me, for simple debugging that's what I use.
If you're really serious about it being right all the way down, try looking at Formatters and printf.

how to set number format to cells using jexcel api

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.

Categories

Resources