0

Because converting between the various float flavors between MS Access (yes: yikes!), Java, and SQLite are so fraught with frustration, I want to store the reals as ints in SQLite. Is the preferred way of accomplishing this like so (pseudocode):

//real r = 36.57
string realAsStr = r.ToString();
// realAsStr is now "36.57"
// strip out the decimal point so that realAsStr becomes "3657"
int strAsInt = (integer)realAsStr; // strAsInt is 3657

...or like so:

int realAsInt = r * 100; // r * 100 is 3657.0[0]; realAsInt = 3657

...or like some other so?

Note: these vals stored as real types in MS Access are monetary values, stored as doubles.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    Just remember if there is any decimals in your data and you put it in an int it will always truncate everything after the decimal. In case you have fractions of pennies you need to carry over. – CodeCamper Apr 14 '14 at 16:12
  • At http://stackoverflow.com/questions/13467849/double-multiplied-by-100-and-then-cast-to-long-is-giving-wrong-value, there is a theoretical answer for the propeller-heads; for those who just want a practical solution, it appears to be: long l =Math.round(r*100); – B. Clay Shannon-B. Crow Raven Apr 14 '14 at 16:22

2 Answers2

1

Simply multiply the real value with 10^x where x is the number of relevant digits after comma.

Then round or truncate, and assign to int.

Example:

Asume 3 digits after comma is relevant for your application:

double doubleVal = 127.123;
int intVal = (int) doubleVal * 1E3; // 1E3 = 1* 10^3 = 1000.0;
// intVal now is 127123

When reading back simply divide by 10^x:

intVal = 127123; // from DB
double val = intVal / 1E3;

// val now 127.123;

AlexWien
  • 28,470
  • 6
  • 53
  • 83
0

A few steps are necessary:

0) Change the data type of the class members in question to "long":

private long _cost;
private long _margin;
private long _listPrice;

1) When reading the values returned from the RESTful method (json), convert them from double to long:

Double cost = jsonObj.getDouble("cost");
Double margin = jsonObj.getDouble("margin");
Double listPrice = jsonObj.getDouble("listPrice");
long costAsLong = Math.round(cost*100);
long marginAsLong = Math.round(margin*100);
long listPriceAsLong = Math.round(listPrice*100);

DeliveryItem delItem = new DeliveryItem();
. . .
delItem.set_cost(costAsLong);
delItem.set_margin(marginAsLong);
delItem.set_listPrice(listPriceAsLong);
. . .

2) When displaying the values, display them as currency. IOW, what is stored as 3657 will display as $36.57

UPDATE

Updated based on AlexWien's answer to follow this pattern:

final double FLOAT_TO_INT_FACTOR = 100.0;
. . .
int costAsInt = (int) Math.round(cost*FLOAT_TO_INT_FACTOR);

(Class members have been changed from long to int)

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862