Input decimal or double numbers in JAVA - java

How can I input a decimal or double number as it is? I want if I input .56 it saves in the database as .56 not 1 because its rounding up and I want to ignore the rounding...
This is servlet, well I have beans and its also set to double; I also tried DecimalFormat but still not working or maybe I just don't know how to use it.
neutrophils = rs.getInt("neutrophils");
monocytes = rs.getInt("monocytes");
eosinophils = rs.getInt("eosinophils");
basophils = rs.getInt("basophils");
lymphocytes = rs.getInt("lymphocytes");
total= (neutrophils + monocytes + eosinophils + eosinophils + basophils + lymphocytes);
I made it like this, I changed the value of datatype to VARCHAR but the error is java.lang.NullPointerException; why is that?
neutrophils = Double.parseDouble(rs.getString("neutrophils"));
monocytes = Double.parseDouble(rs.getString("monocytes"));
eosinophils = Double.parseDouble(rs.getString("eosinophils"));
basophils = Double.parseDouble(rs.getString("basophils"));
lymphocytes = Double.parseDouble(rs.getString("lymphocytes"));
bands = (neutrophils + monocytes + eosinophils + eosinophils + basophils + lymphocytes);

If rs is ResultSet you can simply use rs.getDouble. If for some reason you don't want to use it, get the result as a String and then convert
Double.parseDouble(rs.getString(ColumnLabel));

Related

LDAP with Jacob-ADO-Wrapper

after a little bit of trying I managed to get results from the ldap-server at my company. Now I have a little problem and I seem to be too dump to find any documentation about it.
Command objCmd = new Command();
Recordset RS = new Recordset();
objCmd.setActiveConnection(conn);
objCmd.setCommandText("<LDAP://scdldap.siemens.net:389>;(&(objectClass=scdInternetPerson)(mail=" + email + "));" +searchKeyword+";subTree");
RS = objCmd.Execute();
if (RS.getBOF())
System.out.printf(email + ";" + "null" + "\n");
else {
RS.MoveFirst();
System.out.printf(email + ";" + RS.getFields().getItem(0).getValue() + "\n");
}
This works fine as long as I print the result out to the console. But I would need to get the value as a String (it is always a String), but I can't make it. Can somebody tell me what I am missing? I know this is some VariableType Error, because the result is of type Variant, but
Variant.toString() or anything else is not possible.
Try to convert Variant to Object and then to String, for example:
Variant From = new Variant(1);
Variant To = new Variant(6);
Object[] args = new Object[]{From, To};
String From1 = args[0].toString();
String To1 = args[1].toString();

Android SQLite Database - Not reading decimal part of float from database

This is my first SQLite database with a float. I can't figure out why I am unable to store/retrieve the decimal parts of a float.
The database is defined as:
#Override
public void onCreate(SQLiteDatabase db){
// Create a string that contains the SQL statement to create the Nbmc device table
String SQL_CREATE_NBMC_TEMP_DATA_TABLE = "CREATE TABLE " + NbmcContract.NmbcTempData.TABLE_NAME + " ("
+ NbmcContract.NmbcTempData._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NbmcContract.NmbcTempData.COLUMN_TIMESTAMP + " TEXT NOT NULL, "
+ NbmcContract.NmbcTempData.COLUMN_DATA_FLOAT + " REAL) ";
db.execSQL(SQL_CREATE_NBMC_TEMP_DATA_TABLE);
}
I store floating point data in it from a service activity:
private static double lastSensorTempReading;
// ============ TEMP ==================
else if (UUID_SENSOR_FFF2.equals(characteristic.getUuid())) {
rxSensorDataType = FFF2_TEMP_CONST;
descStringBuilder.append("Elapsed Time: " + timeFormat.format(timeDiff) + "\n");
// temp comes in two bytes: newData[MSB], newData[LSB]
// temp = MSB + (0.1 * LSB)
int iTempMsb_i = (int) newData[0] & 0xff ;
int iTempLsb_i = (int) newData[1] & 0xff;
lastSensorTempReading = (float)iTempMsb_i + (0.10 * (float)iTempLsb_i);
Log.v("broadcastUpdate","Temp = " + lastSensorTempReading);
// Add this data to the temp Db
tempValues.put(NbmcContract.NmbcTempData.COLUMN_TIMESTAMP, estimatedTime);
tempValues.put(NbmcContract.NmbcTempData.COLUMN_DATA_FLOAT, lastSensorTempReading);
newRowId = db_temp.insert(NbmcContract.NmbcTempData.TABLE_NAME, null, tempValues);
}
And, when I use the Log.v to dump the value I think I am storing it looks correct (and it looks correct when I send it to the Main Activity via an intent).
V/broadcastUpdate: Temp = 33.3
However, when I read it back from the SQLite database in my MainActivity, I'm losing the part of the float/double that follows the decimal point but I'm not getting errors reported in the Logcat.
sb.append(" ------------------- Temperature Data -------------------------\n");
nbmcTempDbHelper = new NbmcTempDataDbHelper( this.getApplicationContext());
SQLiteDatabase tmpDb = nbmcTempDbHelper.getReadableDatabase();
c = tmpDb.rawQuery(" SELECT " + NbmcContract.NmbcTempData._ID + ", "
+ NbmcContract.NmbcTempData.COLUMN_TIMESTAMP + ", "
+ NbmcContract.NmbcTempData.COLUMN_DATA_FLOAT +
" FROM " + NbmcContract.NmbcTempData.TABLE_NAME +
" LIMIT " + MAX_RESULTS_RETRIEVED + " OFFSET " + 0, null);
try {
if (c != null) {
if (c.moveToFirst()) {
do {
String tempRowId = c.getString(c.getColumnIndexOrThrow(NbmcContract.NmbcTempData._ID));
String tempTimeString = c.getString(c.getColumnIndexOrThrow(NbmcContract.NmbcTempData.COLUMN_TIMESTAMP));
double tempDataDbl = c.getInt(c.getColumnIndexOrThrow(NbmcContract.NmbcTempData.COLUMN_DATA_FLOAT));
Log.v("getEmailText", "Temp reading = " + tempDataDbl);
sb.append(tempRowId);
sb.append(DELIMITER);
sb.append(tempTimeString);
sb.append(DELIMITER);
sb.append(tempDataDbl);
sb.append(NEW_LINE);
} while (c.moveToNext());
}
}
} finally {
c.close();
tmpDb.close();
}
V/getEmailText: Temp reading = 30.0
V/getEmailText: Temp reading = 30.0
V/getEmailText: Temp reading = 30.0
V/getEmailText: Temp reading = 30.0
The problem is in this line
double tempDataDbl = c.getInt(c.getColumnIndexOrThrow(NbmcContract.NmbcTempData.COLUMN_DATA_FLOAT));
While you are saving a Double you are retrieving an Integer. Just change the line to
double tempDataDbl = c.getDouble(c.getColumnIndexOrThrow(NbmcContract.NmbcTempData.COLUMN_DATA_FLOAT));
Unfortunately AFAIK there is no way to get type mismatch. If you read through Data Types in SQLite it says :
In SQLite, the datatype of a value is associated with the value itself, not with its container. The dynamic type system of SQLite is backwards compatible with the more common static type systems of other database engines in the sense that SQL statements that work on statically typed databases should work the same way in SQLite. However, the dynamic typing in SQLite allows it to do things which are not possible in traditional rigidly typed databases.
Since any container e.g. INTEGER or REAL in your case can hold any and all kinds of data types and not even the database knows which type it is reading.
yes, dear
issue is at fetch time You having some problem with your code.
double tempDataDbl = c.getInt(c.getColumnIndexOrThrow(NbmcContract.NmbcTempData.COLUMN_DATA_FLOAT));
change it to
double tempDataDbl = c.getDouble(c.getColumnIndexOrThrow(NbmcContract.NmbcTempData.COLUMN_DATA_FLOAT));

Translating functionality between java and python

Hi I have the following function in java which seems to work as anticipated in calculating the maximum drawdown.
The function is the following:
DecimalFormat df = new DecimalFormat("########");
double max_dd = 100;
for(double t0:returns.keySet()){
for(double t1:returns.keySet()){
if(t1>t0){
double r = returns.get(t1)/returns.get(t0)-1;
if(r<max_dd){
max_dd = r;
System.out.println(df.format(t1) +"," +df.format( t0) + "," + max_dd + "," +returns.get(t1) + "," + returns.get(t0));
}
}
}
}
I get one result here.
Then I run the following function in python:
pd below is pandas, as is common notation.
def max_dd_(ser):
max2here = pd.expanding_max(ser)
dd2here = ser - max2here
return dd2here.min()
And the result is a much different number.
The data is coming from the same source file, and is of the format: Date,Wealth (Eg: 2014-01-1,12.5)
I trust the java code due to the simplicity and transparency, but prefer python due to its conciseness.
Any pointers on what I may be missing here?
The math was different. Py function should be:
def max_dd_(ser):
max2here = pd.expanding_max(ser)
dd2here = ser / max2here - 1
return dd2here.min()

Using Struts2 Tags to Formatting Numbers

I want to format some numbers in our jsp pages.
first i define some resources in my porperties
format.number.with2Decimal={0,number,#0.00}
......
Question1:
i want to know what is the ‘#’ and '0' means?
0.00,#0.00,##.00,###0.00
who can tell me the differences between them? thanks!
Question2:
if i define a BigDecimal type in my action
BigDecimal number1;
Then my page should using a format to show this value,
1.if number1=null then show -NIL-
2.if number1=0 then show -NIL-
3.if number1>0 then show 1.00,3434.98 .....
please ignore number<0
Question3:
change number1 to a String,
1.if number1=null or empty or blank then show -NIL-
2.if number1=Hello then show Hello ....
could you give me help?
Here you go :
<s:property value="getText('{0,number,#,##0.00}',{profit})"/>
This is how I format numbers in my projects. You can use it with <s:if> to attain what you require.
Question1: i want to know what is the ‘#’ and '0' means?
0.00,#0.00,##.00,###0.00 who can tell me the differences between them? thanks!
0 means that a number must be printed, no matter if it exists
# means that a number must be printed if it exists, omitted otherwise.
Example:
System.out.println("Assuming US Locale: " +
"',' as thousand separator, " +
"'.' as decimal separator ");
NumberFormat nf = new DecimalFormat("#,##0.0##");
System.out.println("\n==============================");
System.out.println("With Format (#,##0.0##) ");
System.out.println("------------------------------");
System.out.println("1234.0 = " + nf.format(1234.0));
System.out.println("123.4 = " + nf.format(123.4));
System.out.println("12.34 = " + nf.format(12.34));
System.out.println("1.234 = " + nf.format(1.234));
System.out.println("==============================");
nf = new DecimalFormat("#,000.000");
System.out.println("\n==============================");
System.out.println("With Format (#,000.000) ");
System.out.println("------------------------------");
System.out.println("1234.0 = " + nf.format(1234.0));
System.out.println("123.4 = " + nf.format(123.4));
System.out.println("12.34 = " + nf.format(12.34));
System.out.println("1.234 = " + nf.format(1.234));
System.out.println("==============================");
Running Example
Output:
Assuming US Locale: ',' as thousand separator, '.' as decimal separator)
==============================
With Format (#,##0.0##)
------------------------------
1234.0 = 1,234.0
123.4 = 123.4
12.34 = 12.34
1.234 = 1.234
==============================
==============================
With Format (#,000.000)
------------------------------
1234.0 = 1,234.000
123.4 = 123.400
12.34 = 012.340
1.234 = 001.234
==============================
In Struts2, you can apply this kind of format with the getText() function from ActionSupport.
P.S: Question 2 and 3 are trivial (and messy).

How to use Rhino library to use javascript code in Java?

I am working on a GPS app and I want to convert my latitudes and longitudes into x-y coordinates based on WGS84 datum. I found this js page to do this: http://www.uwgb.edu/dutchs/usefuldata/ConvertUTMNoOZ.HTM. I also had a look at other calculators but this one is more accurate. Now if you see the source, functions to perform conversion is being provided. I googled how can I use js code in Java and found out that this library can be used to do this: http://www.mozilla.org/rhino/. I added jar to my eclipse project and ran examples from here (http://www.mozilla.org/rhino/examples.html) but an not able to figure out how can I use functions from the source code of that page.
function GeogToUTM(){
//Convert Latitude and Longitude to UTM
Declarations();
k0 = 0.9996;//scale on central meridian
b = a*(1-f);//polar axis.
//alert(a+" "+b);
//alert(1-(b/a)*(b/a));
e = Math.sqrt(1 - (b/a)*(b/a));//eccentricity
//alert(e);
//Input Geographic Coordinates
//Decimal Degree Option
latd0 = parseFloat(document.getElementById("DDLatBox0").value);
lngd0 = parseFloat(document.getElementById("DDLonBox0").value);
latd1 = Math.abs(parseFloat(document.getElementById("DLatBox0").value));
latd1 = latd1 + parseFloat(document.getElementById("MLatBox0").value)/60;
latd1 = latd1 + parseFloat(document.getElementById("SLatBox0").value)/3600;
if (parseFloat(document.getElementById("DLatBox0").value)<0){latd1=-latd1;}
lngd1 = Math.abs(parseFloat(document.getElementById("DLonBox0").value));
lngd1 = lngd1 + parseFloat(document.getElementById("MLonBox0").value)/60;
lngd1 = lngd1 + parseFloat(document.getElementById("SLonBox0").value)/3600;
if (parseFloat(document.getElementById("DLonBox0").value)<0){lngd1=-lngd1;}
lngd=lngd0;
latd=latd0;
if(isNaN(latd)){
latd = latd1;
document.getElementById("DDLatBox0").value = Math.floor(1000000*latd)/1000000;
lngd=lngd1;
document.getElementById("DDLonBox0").value = Math.floor(1000000*lngd)/1000000;
}
if(isNaN(lngd)){lngd = latd1;}
if(isNaN(latd)|| isNaN(lngd)){
alert("Non-Numeric Input Value");
}
if(latd <-90 || latd> 90){
alert("Latitude must be between -90 and 90");
}
if(lngd <-180 || lngd > 180){
alert("Latitude must be between -180 and 180");
}
xd = lngd;
yd = latd;
DDtoDMS();
//Read Input from DMS Boxes
document.getElementById("DLatBox0").value = Math.floor(ydd);
document.getElementById("MLatBox0").value = ym;
document.getElementById("SLatBox0").value = Math.floor(1000*ys)/1000;
document.getElementById("DLonBox0").value = Math.floor(xdd);
document.getElementById("MLonBox0").value = xm;
document.getElementById("SLonBox0").value = Math.floor(1000*xs)/1000;
phi = latd*drad;//Convert latitude to radians
lng = lngd*drad;//Convert longitude to radians
utmz = 1 + Math.floor((lngd+180)/6);//calculate utm zone
latz = 0;//Latitude zone: A-B S of -80, C-W -80 to +72, X 72-84, Y,Z N of 84
if (latd > -80 && latd < 72){latz = Math.floor((latd + 80)/8)+2;}
if (latd > 72 && latd < 84){latz = 21;}
if (latd > 84){latz = 23;}
zcm = 3 + 6*(utmz-1) - 180;//Central meridian of zone
//alert(utmz + " " + zcm);
//Calculate Intermediate Terms
e0 = e/Math.sqrt(1 - e*e);//Called e prime in reference
esq = (1 - (b/a)*(b/a));//e squared for use in expansions
e0sq = e*e/(1-e*e);// e0 squared - always even powers
//alert(esq+" "+e0sq)
N = a/Math.sqrt(1-Math.pow(e*Math.sin(phi),2));
//alert(1-Math.pow(e*Math.sin(phi),2));
//alert("N= "+N);
T = Math.pow(Math.tan(phi),2);
//alert("T= "+T);
C = e0sq*Math.pow(Math.cos(phi),2);
//alert("C= "+C);
A = (lngd-zcm)*drad*Math.cos(phi);
//alert("A= "+A);
//Calculate M
M = phi*(1 - esq*(1/4 + esq*(3/64 + 5*esq/256)));
M = M - Math.sin(2*phi)*(esq*(3/8 + esq*(3/32 + 45*esq/1024)));
M = M + Math.sin(4*phi)*(esq*esq*(15/256 + esq*45/1024));
M = M - Math.sin(6*phi)*(esq*esq*esq*(35/3072));
M = M*a;//Arc length along standard meridian
//alert(a*(1 - esq*(1/4 + esq*(3/64 + 5*esq/256))));
//alert(a*(esq*(3/8 + esq*(3/32 + 45*esq/1024))));
//alert(a*(esq*esq*(15/256 + esq*45/1024)));
//alert(a*esq*esq*esq*(35/3072));
//alert(M);
M0 = 0;//M0 is M for some origin latitude other than zero. Not needed for standard UTM
//alert("M ="+M);
//Calculate UTM Values
x = k0*N*A*(1 + A*A*((1-T+C)/6 + A*A*(5 - 18*T + T*T + 72*C -58*e0sq)/120));//Easting relative to CM
x=x+500000;//Easting standard
y = k0*(M - M0 + N*Math.tan(phi)*(A*A*(1/2 + A*A*((5 - T + 9*C + 4*C*C)/24 + A*A*(61 - 58*T + T*T + 600*C - 330*e0sq)/720))));//Northing from equator
yg = y + 10000000;//yg = y global, from S. Pole
if (y < 0){y = 10000000+y;}
//Output into UTM Boxes
document.getElementById("UTMzBox1").value = utmz;
document.getElementById("UTMeBox1").value = Math.round(10*(x))/10;
document.getElementById("UTMnBox1").value = Math.round(10*y)/10;
if (phi<0){document.getElementById("SHemBox").checked=true;}
//document.getElementById("UTMzBox1").value = utmz;
//document.getElementById("UTMeBox1").value = Math.round(10*(500000+x))/10;
document.getElementById("UTMLonZoneBox2").value = utmz;
document.getElementById("UTMLatZoneBox2").value = DigraphLetrsE[latz];
document.getElementById("UTMeBox2").value = Math.round(10*(x-100000*Math.floor(x/100000)))/10;
document.getElementById("UTMnBox2").value = Math.round(10*(y-100000*Math.floor(y/100000)))/10;
//Generate Digraph
MakeDigraph();
document.getElementById("UTMDgBox2").value = Digraph;
}//close Geog to UTM
///////////////////////////////////////////////////////////////////////
I know I can't use this function as is as it is embedded within HTML. But I have never worked on js so it would be easier for me if I am needed to do minimum changes to the code.
If you just want to run JavaScript and you don't particularly care about using Rhino versus the more generic Java Scripting API, please see the following blog post I wrote:
http://springinpractice.com/2012/05/13/how-to-run-javascript-from-java/
If in fact you want actual Rhino code for whatever reason, here's some sample code that uses Rhino:
https://github.com/springinpractice/sip09/blob/03/src/main/java/com/springinpractice/ch09/comment/service/impl/RichTextFilter.java
You will have to ask if you can use it first - but he says he's generally happy to give people permission to use his work.
All the calls to document.getElementById refer to inputs on the html page.
You'll have to rewrite the function so that you pass these variables to it - as you won't have access to the javascript dom when you run it.
You'll have to work out what you want it to return too, it looks like it displays calculated values across a few fields so you'll probably have to return a map of the fieldname to the calculated value - then you will be to use the results in your java program.
The script you posted also refers to these functions that are missing, so you'll have to find them too, and include them in your script:
MakeDigraph();
DDtoDMS();
Declarations();
I'd recommend that you remove the validation bit of the code with the alerts and just handle this is your java code
It's not going to be very efficient but if that doesn't matter then good luck!

Categories