java - Split number into an integer and decimal -


input 23.893 become integer - 23, decimal - 0.893

here's key snippet code

double realnumber = scan.nextdouble(); \\store keyboard input in variable realnumber  double integerpart = math.floor(realnumber); \\round down eg. 23.893 --> 23  double fractionpart = realnumber - integerpart; \\find remaining decimal 

when try long numbers decimal part differs actual.

input - 234.324112341234134 becomes integer - 234.0,

decimal - 0.3241123412341267

as stated @dasblinkenlight can use methods bigdecimal , combine them splitter. wouldn't count decimal points though, easier stick bigdecimal.

for example:

public static void main(string[] args) {             string realnumber = "234.324823783782";       string[] mysplit = realnumber.split("\\.");      bigdecimal decimal = new bigdecimal(mysplit[0]);     bigdecimal real = new bigdecimal(realnumber);     bigdecimal fraction = real.subtract(decimal);      system.out.println(string.format("decimal : %s\nfraction: %s", decimal.tostring(),fraction.tostring()));  } 

this outputs following: decimal : 234 fraction: 0.324823783782


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -