Int or float
Hello,
In my J2ee server, I have a lots of computation of money. Usually, the primitive type float is satisfied for presenting money. But I have a question, is it better to use int to store it. Even in database, I can save more space by using INT than using DECIMAL(10,2). My MySql, INT requires 4 bytes, DECIMAL(10,2) requires 12 bytes. At I/O moudle, I just simply multiply 100 for input and divid 100 for output. Because I suspect that using float may change a tiny bit at the end of the value. Any suggestions to me?
Thanks!
How are we saying opposite things? I said that he should use an int unless it doesn't matter if the results of a calculation are actually correct. Floats/doubles are generally a bad idea to use unless you know what you are doing, since the approximating effect they have on calculations can be strange to a newcomer. For printing the results of money calculations, floats might work fine. However, you will get a certain amount of error, so you just have to watch out. If you are not storing the results of calculations where the operands are floats, then the error might be ok.
Rounding in accounting programs, like interest programs always have very specific business rules that specify to what degree of precision the calculation is to be performed and which style of rounding should be used. I most programs that need to deal with money, the smallest increment will usually be a cent (for US money anyway). And if they don't have specific rules, then maybe you should get some (or stash the error into an account in your name, Superman 2 thank you very much).
BigDecimal is fine to use if you don't need to worry about speed, and if you have the possibility of overflow with longs, BigDecimal is probably a good idea since it can represent huge numbers that long cannot. I would imagine that most programs don't need more precision then a long can provide.
Similar Messages
-
How do I properly convert an int to a float?
I input a number such as 0x42c26163
The final number should be 97.19021
I thought I could just do a cast so I tried this:
int test = 0x42c26163;
float test2 = (float)test;
But test2 comes up 1.120035171 E9
How do I get to the final 97.19021?
In another project I'm working on using C#, the conversion works when I use the BitConverter class.
I'm sure I am just overlooking the obvious, but can someone can help me?I suppose that int number is really the content of a float read back from raw memory or received from an instrument or on some communication channel. Rebuilding the float number has been discussed a couple of ways in the forums: I can suggest you look at this thread or this other one which give you feasible solutions.
This is basically a reflect of how floating point numbers are stored in memory according to IEEE754 standard, which you may want to take a look at to understand a bit how all the matter is treated.
Proud to use LW/CVI from 3.1 on.
My contributions to the Developer Zone Community
If I have helped you, why not giving me a kudos? -
How to determine INT and FLOAT in a DECODE statement
Can anyone help me with the following problem:
I have a column defined as a NUMBER(15,4). I am trying to determine the java type using the getScale() method in ResultSetMetaData. When the scale is greater than 0, then it is an float, else it is an int. In this case, the getScale() method should return 4. However, when querying with a DECODE statement on the NUMBER(15,4) field, the getScale() method always returns 0 and the value is therefore converted to an int. Anyone knows how to solve this problem?
ThanksAlcides,
Oracle NUMBER data type is mapped to "java.math.BigDecimal" class.
You will find more information in the JDBC Developer's Guide and Reference which is part of the Oracle documentation and available from:
http://www.oracle.com/technology/documentation/index.html
Good Luck,
Avi. -
Using ints or floats for Color
Thanks in advance for taking time to read this message.
I am using "Color" and need the most accurate color rendering. I found that I was losing some accuracy with Color(int, int, int), with integers ranging from 0-255. Because of this loss of accuracy, I am contemplating using Color(float, float, float) to make my colors. The float values can range from 0 - 1.
"Theoretically" using integers one can effectively create 256^3 colors. How many colors can be created when using floats? More importantly, how do the float produced colors correspond to the more widely used int colors?
Thanks,
Every_manAssuming you want a RGB color scheme, you could get approx (2^22)^3 different colors, since a float has 2^22 bits for the mantissa (assuming you want an even spread between 0 and 1).
When using Color(float, float, float) Java will try to map these values to the available system as best as possible. Therefore if your system can hadle more than 256 values for each of the RGB values you should get better color resolution.
If you system does not use RGB encoding, you should probably use Color(ColorSpace, float[], float) -
Float type problem helppppppppp
I have a jsp page, which retrieves values from a html page, my problem is that
i can insert the values in database, but the problem is that it does not insert the flot type values...
like 21.21, 242.52. It shows only 21,242
it does not shows in float type.
html form:
<input type="text" name="code" size="5" maxlength="5">
<input type="text" name="Description" size="65">
<input type="text" name="DrAmount" size="12" >
<input type="text" name="CrAmount" size="12" >
<SELECT name="type">
<option value="" selected></option>
<option VALUE="C">C</option>
<option VALUE="O">O</option>
<option VALUE="OI">OI</option>
<option VALUE="OR">OR</option>
<option VALUE="S">S</option>
<option VALUE="SB">SB</option>
<option VALUE="SG">SG</option></select>
<input name="pct" type="text" size="6" maxlength="5" >
jsp page:
<html>
<head>
<%@ page
import = "java.io.*"
import = "java.lang.*"
import = "java.sql.*"
%>
<title></title>
</head>
<body>
<h1></h1>
<%
String Code,Description,Dr_Amount,Cr_Amount,Pct,Type, sql1 ;
ResultSet results;
PreparedStatement sql;
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:pf","scott","ttlscott");
try
int gl_code;
Float db_amt,cr_amt,gl_pct;
String gl_descr, gl_type;
boolean doneheading = false;
Statement s=conn.createStatement();
Code = request.getParameter("code");
Description = request.getParameter("Description");
Dr_Amount=request.getParameter("DrAmount");
Cr_Amount=request.getParameter("CrAmount");
Type = request.getParameter("type");
Pct=request.getParameter("pct");
PreparedStatement pstmt = conn.prepareStatement(
("INSERT INTO gl_mast VALUES (?, ?, ?, ?, ?,?)"));
pstmt.setInt(1,Integer.parseInt(request.getParameter("Code")));
pstmt.setString(2, request.getParameter("Description"));
pstmt.setFloat(3,Float.parseFloat(request.getParameter("Dr_Amount")));
pstmt.setFloat(4,Float.parseFloat(request.getParameter("Cr_Amount")));
pstmt.setString(5, request.getParameter("Type"));
pstmt.setFloat(6,Float.parseFloat(request.getParameter("Pct")));
pstmt.executeUpdate();
sql = conn.prepareStatement("SELECT * FROM gl_mast WHERE gl_code = '" + Code + "'");
results = sql.executeQuery();
while(results.next())
if(! doneheading)
out.println("<table border=2>");
doneheading = true;
gl_code = results.getInt("gl_code");
gl_descr = results.getString("gl_descr");
db_amt = results.getFloat("db_amt");
cr_amt = results.getFloat("cr_amt");
gl_type = results.getString("gl_type");
gl_pct = results.getFloat("gl_pct");
out.println("<BODY bgColor=blanchedalmond text=#008000 topMargin=0>");
out.println("<P align=center><FONT face=Helvetica><FONT color=fuchsia > <BIG>GL MASTER INFORMATION</BIG></FONT></P>");
out.println("<P align=center>");
out.println("<TABLE align=center border=1 cellPadding=1 cellSpacing=1 width=\"75%\">");
out.println("<TR>");
out.println("<TD>Code No.</TD>");
out.println("<TD>Description</TD>");
out.println("<TD>Dr. Amount</TD>");
out.println("<TD>Cr. Amount</TD>");
out.println("<TD>Type</TD>");
out.println("<TD>Percentage</TD></TR>");
out.println("<tr><td>" + gl_code);
out.println("<td>" + gl_descr);
out.println("<td>" + db_amt);
out.println("<td>" + cr_amt);
out.println("<td>" + gl_type);
out.println("<td>" + gl_pct);
if(doneheading)
out.println("</table>");
else
out.println("No matches for " + Code);
catch (SQLException s)
out.println("Dupliacte Entry<br>");
catch (ClassNotFoundException err)
out.println("Class loading error");
%>
</body>
</html>
error:
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: Unable to compile class for JSP
An error occurred at line: 13 in the jsp file: /gl_master/gl_save.jsp
Generated servlet error:
D:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\abhi\org\apache\jsp\gl_005fmaster\gl_005fsave_jsp.java:100: incompatible types
found : float
required: java.lang.Float
db_amt = results.getFloat("db_amt");
^
An error occurred at line: 13 in the jsp file: /gl_master/gl_save.jsp
Generated servlet error:
D:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\abhi\org\apache\jsp\gl_005fmaster\gl_005fsave_jsp.java:101: incompatible types
found : float
required: java.lang.Float
cr_amt = results.getFloat("cr_amt");
^
An error occurred at line: 13 in the jsp file: /gl_master/gl_save.jsp
Generated servlet error:
D:\Program Files\Apache Software Foundation\Tomcat 5.0\work\Catalina\localhost\abhi\org\apache\jsp\gl_005fmaster\gl_005fsave_jsp.java:103: incompatible types
found : float
required: java.lang.Float
gl_pct = results.getFloat("gl_pct");
^
3 errors
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:332)
org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:437)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:497)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:476)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:464)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:511)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:295)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.0.30 logs.
Apache Tomcat/5.0.30Float db_amt,cr_amt,gl_pct;
found : float
required: java.lang.Float
db_amt = results.getFloat("db_amt");The messages are self-explainatory. You are having objects of type Float. and the ResultSet.getFloat() would return float.
Cheers
-P -
Inline functions in C, gcc optimization and floating point arithmetic issues
For several days I really have become a fan of Alchemy. But after intensive testing I have found several issues which I'd like to solve but I can't without any help.
So...I'm porting an old game console emulator written by me in ANSI C. The code is working on both gcc and VisualStudio without any modification or crosscompile macros. The only platform code is the audio and video output which is out of scope, because I have ported audio and video witin AS3.
Here are the issues:
1. Inline functions - Having only a single inline function makes the code working incorrectly (although not crashing) even if any optimization is enabled or not (-O0 or O3). My current workarround is converting the inline functions to macros which achieves the same effect. Any ideas why inline functions break the code?
2. Compiler optimizations - well, my project consists of many C files one of which is called flash.c and it contains the main and exported functions. I build the project as follows:
gcc -c flash.c -O0 -o flash.o //Please note the -O0 option!!!
gcc -c file1.c -O3 -o file1.o
gcc -c file2.c -O3 -o file2.o
... and so on
gcc *.o -swc -O0 -o emu.swc //Please note the -O0 option again!!!
mxmlc.exe -library-path+=emu.swc --target-player=10.0.0 Emu.as
or file in $( ls *.o ) //Removes the obj files
do
rm $file
done
If I define any option different from -O0 in gcc -c flash.c -O0 -o flash.o the program stops working correctly exactly as in the inline funtions code (but still does not crash or prints any errors in debug). flash has 4 static functions to be exported to AS3 and the main function. Do you know why?
If I define any option different from -O0 in gcc *.o -swc -O0 -o emu.swc the program stops working correctly exactly as above, but if I specify -O1, -O2 or O3 the SWC file gets smaller up to 2x for O3. Why? Is there a method to optimize all the obj files except flash.o because I suspect a similar issue as when compilling it?
3. Flating point issues - this is the worst one. My code is mainly based on integer arithmetic but on 1-2 places it requires flating point arithmetic. One of them is the conversion of 16-bit 44.1 Khz sound buffer to a float buffer with same sample rate but with samples in the range from -1.0 to 1.0.
My code:
void audio_prepare_as()
uint32 i;
for(i=0;i<audioSamples;i+=2)
audiobuffer[i] = (float)snd.buffer[i]/32768;
audiobuffer[i+1] = (float)snd.buffer[i+1]/32768;
My audio playback is working perfectly. But not if using the above conversion and I have inspected the float numbers - all incorrect and invalid. I tried other code with simple floats - same story. As if alchemy refuses to work with floats. What is wrong? I have another lace whre I must resize the framebuffer and there I have a float involved - same crap. Please help me?
Found the floating point problem: audiobuffer is written to a ByteArray and then used in AS. But C floats are obviously not the same as those in AS3. Now the floating point is resolved.
The optimization issues remain! I really need to speed up my code.
Thank you in advice!Dear Bernd,
I am still unable to run the optimizations and turn on the inline functions. None of the inline functions contain any stdli function just pure asignments, reads, simple arithmetic and bitwise operations.
In fact, the file containing the main function and those functions for export in AS3 did have memset and memcpy. I tried your suggestion and put the code above the functions calling memset and memcpy. It did not work soe I put the code in a header which is included topmost in each C file. The only system header I use is malloc.h and it is included topmost. In other C file I use pow, sin and log10 from math.h but I removed it and made the same thing:
//shared.h
#ifndef _SHARED_H_
#define _SHARED_H_
#include <malloc.h>
static void * custom_memmove( void * destination, const void * source, unsigned int num ) {
void *result;
__asm__("%0 memmove(%1, %2, %3)\n" : "=r"(result) : "r"(destination), "r"(source), "r"(num));
return result;
static void * custom_memcpy ( void * destination, const void * source, unsigned int num ) {
void *result;
__asm__("%0 memcpy(%1, %2, %3)\n" : "=r"(result) : "r"(destination), "r"(source), "r"(num));
return result;
static void * custom_memset ( void * ptr, int value, unsigned int num ) {
void *result;
__asm__("%0 memset(%1, %2, %3)\n" : "=r"(result) : "r"(ptr), "r"(value), "r"(num));
return result;
static float custom_pow(float x, int y) {
float result;
__asm__("%0 pow(%1, %2)\n" : "=r"(result) : "r"(x), "r"(y));
return result;
static double custom_sin(double x) {
double result;
__asm__("%0 sin(%1)\n" : "=r"(result) : "r"(x));
return result;
static double custom_log10(double x) {
double result;
__asm__("%0 log10(%1)\n" : "=r"(result) : "r"(x));
return result;
#define memmove custom_memmove
#define memcpy custom_memcpy
#define memset custom_memset
#define pow custom_pow
#define sin custom_sin
#define log10 custom_log10
#include "types.h"
#include "macros.h"
#include "m68k.h"
#include "z80.h"
#include "genesis.h"
#include "vdp.h"
#include "render.h"
#include "mem68k.h"
#include "memz80.h"
#include "membnk.h"
#include "memvdp.h"
#include "system.h"
#include "loadrom.h"
#include "input.h"
#include "io.h"
#include "sound.h"
#include "fm.h"
#include "sn76496.h"
#endif /* _SHARED_H_ */
It still behave the same way as if nothing was changed (works incorrectly - displays jerk which does not move, whereby the image is supposed to move)
As I am porting an emulator (Sega Mega Drive) I use manu arrays of function pointers for implementing the opcodes of the CPU's. Could this be an issue?
I did a workaround for the floating point problem but processing is very slow so I hear only bzzt bzzt but this is for now out of scope. The emulator compiled with gcc runs at 300 fps on a 1.3 GHz machine, whereby my non optimized AVM2 code compiled by alchemy produces 14 fps. The pure rendering is super fast and the problem lies in the computational power of AVM. The frame buffer and the enulation are generated in the C code and only the pixels are copied to AS3, where they are plotted in a BitmapData. On 2.0 GHz Dual core I achieved only 21 fps. Goal is 60 fps to have smooth audio and video. But this is offtopic. After all everything works (slow) without optimization, and I would somehow turn it on. Suggestions?
Here is the file with the main function:
#include "shared.h"
#include "AS3.h"
#define FRAMEBUFFER_LENGTH (320*240*4)
static uint8* framebuffer;
static uint32 audioSamples;
AS3_Val sega_rom(void* self, AS3_Val args)
int size, offset, i;
uint8 hardware;
uint8 country;
uint8 header[0x200];
uint8 *ptr;
AS3_Val length;
AS3_Val ba;
AS3_ArrayValue(args, "AS3ValType", &ba);
country = 0;
offset = 0;
length = AS3_GetS(ba, "length");
size = AS3_IntValue(length);
ptr = (uint8*)malloc(size);
AS3_SetS(ba, "position", AS3_Int(0));
AS3_ByteArray_readBytes(ptr, ba, size);
//FILE* f = fopen("boris_dump.bin", "wb");
//fwrite(ptr, size, 1, f);
//fclose(f);
if((size / 512) & 1)
size -= 512;
offset += 512;
memcpy(header, ptr, 512);
for(i = 0; i < (size / 0x4000); i += 1)
deinterleave_block(ptr + offset + (i * 0x4000));
memset(cart_rom, 0, 0x400000);
if(size > 0x400000) size = 0x400000;
memcpy(cart_rom, ptr + offset, size);
/* Free allocated file data */
free(ptr);
hardware = 0;
for (i = 0x1f0; i < 0x1ff; i++)
switch (cart_rom[i]) {
case 'U':
hardware |= 4;
break;
case 'J':
hardware |= 1;
break;
case 'E':
hardware |= 8;
break;
if (cart_rom[0x1f0] >= '1' && cart_rom[0x1f0] <= '9') {
hardware = cart_rom[0x1f0] - '0';
} else if (cart_rom[0x1f0] >= 'A' && cart_rom[0x1f0] <= 'F') {
hardware = cart_rom[0x1f0] - 'A' + 10;
if (country) hardware=country; //simple autodetect override
//From PicoDrive
if (hardware&8)
hw=0xc0; vdp_pal=1;
} // Europe
else if (hardware&4)
hw=0x80; vdp_pal=0;
} // USA
else if (hardware&2)
hw=0x40; vdp_pal=1;
} // Japan PAL
else if (hardware&1)
hw=0x00; vdp_pal=0;
} // Japan NTSC
else
hw=0x80; // USA
if (vdp_pal) {
vdp_rate = 50;
lines_per_frame = 312;
} else {
vdp_rate = 60;
lines_per_frame = 262;
/*SRAM*/
if(cart_rom[0x1b1] == 'A' && cart_rom[0x1b0] == 'R')
save_start = cart_rom[0x1b4] << 24 | cart_rom[0x1b5] << 16 |
cart_rom[0x1b6] << 8 | cart_rom[0x1b7] << 0;
save_len = cart_rom[0x1b8] << 24 | cart_rom[0x1b9] << 16 |
cart_rom[0x1ba] << 8 | cart_rom[0x1bb] << 0;
// Make sure start is even, end is odd, for alignment
// A ROM that I came across had the start and end bytes of
// the save ram the same and wouldn't work. Fix this as seen
// fit, I know it could probably use some work. [PKH]
if(save_start != save_len)
if(save_start & 1) --save_start;
if(!(save_len & 1)) ++save_len;
save_len -= (save_start - 1);
saveram = (unsigned char*)malloc(save_len);
// If save RAM does not overlap main ROM, set it active by default since
// a few games can't manage to properly switch it on/off.
if(save_start >= (unsigned)size)
save_active = 1;
else
save_start = save_len = 0;
saveram = NULL;
else
save_start = save_len = 0;
saveram = NULL;
return AS3_Int(0);
AS3_Val sega_init(void* self, AS3_Val args)
system_init();
audioSamples = (44100 / vdp_rate)*2;
framebuffer = (uint8*)malloc(FRAMEBUFFER_LENGTH);
return AS3_Int(vdp_rate);
AS3_Val sega_reset(void* self, AS3_Val args)
system_reset();
return AS3_Int(0);
AS3_Val sega_frame(void* self, AS3_Val args)
uint32 width;
uint32 height;
uint32 x, y;
uint32 di, si, r;
uint16 p;
AS3_Val fb_ba;
AS3_ArrayValue(args, "AS3ValType", &fb_ba);
system_frame(0);
AS3_SetS(fb_ba, "position", AS3_Int(0));
width = (reg[12] & 1) ? 320 : 256;
height = (reg[1] & 8) ? 240 : 224;
for(y=0;y<240;y++)
for(x=0;x<320;x++)
di = 1280*y + x<<2;
si = (y << 10) + ((x + bitmap.viewport.x) << 1);
p = *((uint16*)(bitmap.data + si));
framebuffer[di + 3] = (uint8)((p & 0x1f) << 3);
framebuffer[di + 2] = (uint8)(((p >> 5) & 0x1f) << 3);
framebuffer[di + 1] = (uint8)(((p >> 10) & 0x1f) << 3);
AS3_ByteArray_writeBytes(fb_ba, framebuffer, FRAMEBUFFER_LENGTH);
AS3_SetS(fb_ba, "position", AS3_Int(0));
r = (width << 16) | height;
return AS3_Int(r);
AS3_Val sega_audio(void* self, AS3_Val args)
AS3_Val ab_ba;
AS3_ArrayValue(args, "AS3ValType", &ab_ba);
AS3_SetS(ab_ba, "position", AS3_Int(0));
AS3_ByteArray_writeBytes(ab_ba, snd.buffer, audioSamples*sizeof(int16));
AS3_SetS(ab_ba, "position", AS3_Int(0));
return AS3_Int(0);
int main()
AS3_Val romMethod = AS3_Function(NULL, sega_rom);
AS3_Val initMethod = AS3_Function(NULL, sega_init);
AS3_Val resetMethod = AS3_Function(NULL, sega_reset);
AS3_Val frameMethod = AS3_Function(NULL, sega_frame);
AS3_Val audioMethod = AS3_Function(NULL, sega_audio);
// construct an object that holds references to the functions
AS3_Val result = AS3_Object("sega_rom: AS3ValType, sega_init: AS3ValType, sega_reset: AS3ValType, sega_frame: AS3ValType, sega_audio: AS3ValType",
romMethod, initMethod, resetMethod, frameMethod, audioMethod);
// Release
AS3_Release(romMethod);
AS3_Release(initMethod);
AS3_Release(resetMethod);
AS3_Release(frameMethod);
AS3_Release(audioMethod);
// notify that we initialized -- THIS DOES NOT RETURN!
AS3_LibInit(result);
// should never get here!
return 0; -
Int printing out as scientific notation
maybe doing something stupid here but I can't seem to pick it up.
I have a Window that calls a subclass to display a calculator, and then returns the final value to the Window, if I input 10 digits it prints on as a 12345678E5
something like that.
Anywho here's the two methods that deal with value in the subclass( calculator )
public int ReturnNumber(){//the method that will return the value from the keyboard
int final_number = Integer.parseInt(number);
return final_number; // returns value to question screen
private void NextButtonActionPerformed (java.awt.event.ActionEvent evt) {
if ( value.length() != allowable_answers[currentQuestionNumber] ){
JOptionPane.showMessageDialog(this, "Please make a valid entry.", "Invalid",
JOptionPane.WARNING_MESSAGE );
value.replace(0,counter,"");
jTextField1.setText( null );
return;
else {
number = value.toString();
setVisible(false);
frame.final_number = ReturnNumber();
frame.userMakeSelection = true;
frame.FinalTimer.start();
frame.ButtonSelected();Code from window that deals with the number
if(Numeric[currentQuestionNumber]){
currentAnswers[currentQuestionNumber][1] = final_number;// currentAnswers is a float[][]
numeric_question_value[currentQuestionNumber][0] = final_number;// used in poll frequency
}// numeric is a int[]
else
currentAnswers[currentQuestionNumber][currentChoice] = currentChoice;Is from trying to jam an int into float?
Any suggestions
JimIs from trying to jam an int into float?That's exactly the cause. Here are some solutions:
- Use java.text.DecimalFormat to format the output or cast the float to an integer type when you want to print it (presicion might become a problem).
- Keep the number in an int or long all the time. This way you'll not lose any presicion.
Explanation can be found in the API docs of Float.toString():"If the argument is NaN, the result is the string "NaN".
Otherwise, the result is a string that represents the sign and magnitude (absolute value) of the argument. If the sign is negative, the first character of the result is '-' ('-'); if the sign is positive, no sign character appears in the result. As for the magnitude m:
If m is less than 10^-3 or not less than 10^7, then it is represented in so-called "computerized scientific notation." Let n be the unique integer such that 10n<=m<1; then let a be the mathematically exact quotient of m and 10n so that 1<a<10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' (.), followed by decimal digits representing the fractional part of a, followed by the letter 'E' (E), followed by a representation of n as a decimal integer, as produced by the method Integer.toString(int) of one argument." -
Convert float to 4 bytes array
How can I convert float type to 4 byte array -
not with strings but to exact binary representation.See the javadoc of Float.floatToIntBits. Converting an int to an array of 4 bytes is easy, so I will left it as an exercise.
floatToIntBits
public static int floatToIntBits(float value)Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "single format" bit layout.
Bit 31 (the bit that is selected by the mask 0x80000000) represents the sign of the floating-point number. Bits 30-23 (the bits that are selected by the mask 0x7f800000) represent the exponent. Bits 22-0 (the bits that are selected by the mask 0x007fffff) represent the significand (sometimes called the mantissa) of the floating-point number.
If the argument is positive infinity, the result is 0x7f800000.
If the argument is negative infinity, the result is 0xff800000.
If the argument is NaN, the result is 0x7fc00000.
In all cases, the result is an integer that, when given to the intBitsToFloat(int) method, will produce a floating-point value the same as the argument to floatToIntBits (except all NaN values are collapsed to a single "canonical" NaN value).
Parameters:
value - a floating-point number.
Returns:
the bits that represent the floating-point number. -
How to store (non-persistent) multiple float[] arrays.
Hi;
In a situation where an object needs to store multiple float arrays, how can I use a 2 dimensional array to store them? I can't use a collection since an array is a primitive.
I would use a 2 dimensional array, but my keys to get/set these arrays are ints. So I cant do a "int i[][]", nor a "float f[][]".
Any ideas?
Thanks;
-natYou could make a Map (such as HashMap) with an
Integer (java.lang.Integer) key and a "int []" or "float []" as a value (an array is an Object, so can be put as a value).You kid me not! I need to review my basics.
I simply didn't know that an array of primitives can be stored as a value in a map.
Thank you!
-nat -
import java.lang.String;
import java.lang.Integer;
import java.lang.Float;
import java.util.Hashtable;
import java.util.Enumeration;
public class VenkatCart {
protected Hashtable items = new Hashtable();
public VenkatCart() {
public void addItem(String idk,int ic,int size,float rate,int qty) {
String item[]={idk,Integer.toString(ic),Integer.toString(size),Float.toString(rate),Integer.toString(qty)};
if (items.containsKey(idk)) {
String tmpItem[] = (String[])items.get(idk);
int tmpQuant = Integer.parseInt(tmpItem[4]);
qty += tmpQuant;
tmpItem[4] = Integer.toString(qty);
else {
items.put(idk,item);
// get an Enumeration to the list of items in the shopping cart
public Enumeration getEnumeration() {
return items.elements();
// get the total cost of all of the items currently in the shopping cart
public float getCost() {
Enumeration enum = items.elements();
String tmpItem[];
float totalCost = 0.0f;
while (enum.hasMoreElements()) {
tmpItem = (String[])enum.nextElement();
totalCost += (Integer.parseInt(tmpItem[4]) * Float.parseFloat(tmpItem[3]));
return totalCost;
// get the total number of items currently in the shopping cart
public int getNumOfItems() {
Enumeration enum = items.elements();
String tmpItem[];
int numOfItems =0;
while (enum.hasMoreElements()) {
tmpItem = (String[])enum.nextElement();
numOfItems += Integer.parseInt(tmpItem[4]);
return numOfItems;
When I call the method "getCost()" from a jsp program, I get the error message
Error: java.lang.Float: method parseFloat(Ljava/lang/String;)F not found has been reported.
I think the mistake is in conversion.
Please help me.
My thanks in advance.Why don't you try the following:
Float tmpFloat=new Float(tmpItem[3]);
totalCost += (Integer.parseInt(tmpItem[4]) * tmpFloat.floatValue();
Justyna -
Hi
In java int or float or double type are signed type
Why not unsignedIt was a design decision not to include unsigned integral types in Java.
Java's designers might have judged that the difficulties and complicity arising from having signed and unsigned types overweigh the benefits in Java. -
Hi,
I have following code:
float totalSpent;
int intBudget;
float moneyLeft;
totalSpent += Amount;
moneyLeft = intBudget - totalSpent;
And this is how it looks in debugger: http://www.braginski.com/math.tiff
Why would moneyLeft calculated by the code above is .02 different compared to the expression calculated by the debugger?
Expression windows is correct, yet code above produces wrong by .02 result. It only happens for number very large numbers (yet way below int limit)
thanksThank you all for help!
Could someone please point me out why first variable printed incorrect, while second is correct:
NSDecimalNumber *intBalance;
NSDecimalNumber *Amount;
NSDecimalNumber *leftAmount;
NSNumberFormatter *currencyStyle;
NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
scale:2 raiseOnExactness:NO raiseOnOverflow:NO
raiseOnUnderflow:NO raiseOnDivideByZero:NO];
currencyStyle = [[NSNumberFormatter alloc] init];
[currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
intBalance = [NSDecimalNumber decimalNumberWithString:@"999999"];
Amount = [NSDecimalNumber decimalNumberWithString:@"99999.59"];
leftAmount = [intBalance decimalNumberBySubtracting: Amount withBehavior: handler];
NSLog(@"Number is: %.2f, %@", [leftAmount floatValue], [currencyStyle stringFromNumber:leftAmount]);
Number is: 899999.44, $899,999.41
Message was edited by: leonbrag -
Hello Friends,
While preparing for A JAVA test, i came across a strange behavior in java language. will be greatful if somebody can clarify it.
The problem is:
if we try to assign long data type to int without casting explicitly, complier will throw an error, e.g. consider the following piece of code-
int iData2=10000000000000L;
The compiler will say that there is a possible loss of precision.
but if i replace int by float e.g. change the above code to
float fData2=10000000000000L;
the compiler is accepting code without giving any warning that there is a possible loss of precision, although there is such a loss in the output.
is this behaviour justified?you have to draw the line somewhere... so Java just
looks at the range of numbers that can be presented;
for every long there is a float that is fairly close to it.Okay, but the difference between some long values that have been converted to a float are not close at all. For example:
long l = (long)Math.pow(2,63) - 1000000000000L;
float f = l;
long l2 = (long)f;
System.out.println("l is:" + l);
System.out.println("l2 is:" + l2);
System.out.println("l-l2 is:" + (l-l2));
The output is:
l is:9223371036854775807
l2 is:9223370937343148032
l-l2 is:99511627775
I don't call a difference of 99511627775 close. I think you should have to cast a long to a float.
-- MWR
you can't have the compiler complain about
everything, otherwise you woldn't be able to do
anything useful...
for example:
double d = 0.1; // 1
float f = 1;
f = f/10; // 2
double d = d - f; // 3
on line 1: possible loss of precision becausethere
is no double that represents one tenth exactlyCould not really get it. where is the chance ofloss
of precision? In Java, floating point literals areby
default double type. So if u assign double to a
double , there is no chance of loss of precision.By
the way, i executed this code. Compiler didnot
complain and output was "d=0.1"
on line 2: possible loss of precision because
the
result of dividing by a non-power of two cannotbe
represented exactly as a floating point numberhere also, there is no chance of loss ofprecision.
because u r assigning an int literal(32 bit) to a
float variable (also 32 bit).
on line 3: possible loss of precision because
you
subtract near-equal values from each other,producing
a massive relative errorthis is ok.. it will give loss of precision with
compiler complaints. :-)
you have to draw the line somewhere... so Javajust
looks at the range of numbers that can bepresented;
for every long there is a float that is fairlyclose
to it.
srry one rectification..
*this is ok.. it will give loss of precision
without
compiler complaints. :-) -
Dimensions - int and double mixed?
Dimension x = new Dimension(int_1, int_2);
int height = x.height;
int width = x.width;
double height_d = x.getHeight();
double width_d = x.getWidth();When you create a dimension you give it to integers as the width and height. However, if you call getHeight() or getWidth() it returns double-precision values. What's the point? Why does it use int/doubles?
ThanksThe methods getWidth/getHeight are inherited from RectangularShape.
We have:
Rectangle2D extends RectangularShape
Rectagle extends Rectangle2D //implemeted with ints
Rectangle2D .Float extends Rectangle2D //implemeted with floats
Rectangle2D .Double extends Rectangle2D //implemeted with double
So the implementations are providing the precision. Since the getWidth/getHeight methods are common
to the hierarchy they return doubles to avoid loss of precision in the Rectangle2D .Double case.
On the other hand, if I'm working with a java.awt.Rectangle I just access the public width and height fields
directly. -
Easiest way to split a floating point value
Hello, I am trying to split a floating-point value (double) into its fractional and integer parts? I have been trying to find some sort of method in BigDecimal or Double that would do it but so far I haven't come up with anything. I know it could be done by searching through it as a String but that sounds like a very inefficent way to do it. I would appreciate any help you could give. Thanks
float f;
int i = (int) f;
float frac = f-i;
Maybe you are looking for
-
I can no longer access apps on my new iPad that we're downloaded on old iPad. Using cloud.
-
Computer sees monitor-but monitor does not see computer.
I have a MacBookPro with the older 29 pin DVI out. I own an 8.4" HD monitor for video production and want to use it for editing. I am trying to get my Marshall V-R84DP-HD monitor to see the computer and it does not recognize it. I have Mac OS X Versi
-
How does one empty an array during runtime with a front panel switch
I can 'empty array' from the front panel during runtime but I want to empty all arrays (20) from my vi with a front panel switch (see screenshot). I have used replace array subset and reshape array with no success. Any help would be appreciated Attac
-
Problem connecting iPad to Wi Fi
Hi, Lately I'm having problem connecting my iPad to Wi Fi. when I try I get the following message: "hotspot login could not open the page because the server stopped responding" This only happen on new Wi Fi locations. Any one have an idea why it happ
-
TS2972 Apple tv sleeps when computer sleeps. What to do
The TV disconnects from Apple TV sharing when computer sleeps. What to do?