Java – Convert double to int array

  • A+
Category:Languages

I have a double

double pi = 3.1415; 

I want to convert this to a int array

int[] piArray = {3,1,4,1,5}; 

I came up with this

double pi = 3.1415; String piString = Double.toString(pi).replace(".", ""); int[] piArray = new int[piString.length()]; for (int i = 0; i <= piString.length()-1; i++)    piArray[i] = piString.charAt(i) - '0';  

It's working but I don't like this solution because I think a lot of conversions between datatypes can lead to errors. Is my code even complete or do I need to check for something else?

And how would you approach this problem? Wasn't able to find a similar problem here on stackoverflow for Java.

 


I don't know stright way but I think It is simpler:

int[] piArray = String.valueOf(pi).replaceAll("//D", "").chars().map(Character::getNumericValue).toArray(); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: