开发者

Regarding double dataype

开发者 https://www.devze.com 2022-12-22 02:36 出处:网络
I have a double variable test. I want to extract the all digits before decimal point and two digits after the decimal point store the output in integer variables dollar, cents. how can i do it? I dont

I have a double variable test. I want to extract the all digits before decimal point and two digits after the decimal point store the output in integer variables dollar, cents. how can i do it? I dont want any rounding to happen.

example:

double test= 12.1234

Output

int dollar =12;
int cents =12;

double test =1235.0
开发者_开发百科

output

int dollar=1235
int cents =0


For currency, especially when you don't want any rounding, you should use the BigDecimal class. Something like:

BigDecimal test = new BigDecimal("12.1234");
int dollar = test.intValue();
int cents = test.scaleByPowerOfTen(2).intValue() - dollar * 100;


You can do:

double test= 12.1234;
int dollar = (int) test;
int cents = (int) ((test-dollar) * 100);


How about:

dollar = test;
test -= dollar;
cents = test * 100;

Line 1 assigns the integer part of test (12) to the integer 'dollar.' Line 2 removes the 12 dollars from the test value. Line 3 assigns 100 times the fractional part of test to cents. Note that I don't round here. For that, you'd have to:

cents = (test + 0.005) * 100


How about something like this. Rather than printing the values, you can simply assign them as you see fit.

double d = 32.456;
System.out.println( (int)d );
System.out.println( d-(int)d);


String[] s = Double.toString(test).split(".");
String dol = s[0];
String cent = s[1].substring(0,1);


For double values greater than 10^13, there won't be ANY significant digits after the notional decimal point.

You should not be using double or float for representing financial quantities. Use int or long (appropriately scaled and with explicit checks for overflow) or BigDecimal.

0

精彩评论

暂无评论...
验证码 换一张
取 消