NiceToMytyuk
NiceToMytyuk

Reputation: 4277

java.lang.NumberFormatException while formatting a String

I'm getting NumberFormatException: For input string: "4045989016914" while trying to format the string as the following

String.format("%013d", Integer.valueOf(itemMODEL.getCodiceArticolo()))

itemMODEL.getCodiceArticolo is a String that would be a barcode and i would to add 0 if it's shorted than 13 so the code i'm using should be right but i can't get why i'm getting that error.

2018-10-08 16:01:37.420 12670-12670/it.gabtamagnini.realco E/AndroidRuntime: FATAL EXCEPTION: main Process: it.gabtamagnini.realco, PID: 12670 java.lang.NumberFormatException: For input string: "4045989016914" at java.lang.Integer.parseInt(Integer.java:524) at java.lang.Integer.valueOf(Integer.java:611) at it.gabtamagnini.realco.InventarioActivity.Tracciato(InventarioActivity.java:471) at it.gabtamagnini.realco.InventarioActivity$9.onClick(InventarioActivity.java:429) at android.view.View.performClick(View.java:5637) at android.view.View$PerformClick.run(View.java:22433) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6130) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Upvotes: 0

Views: 823

Answers (2)

TheWanderer
TheWanderer

Reputation: 17824

As an alternative to Christopher's answer, you shouldn't even need to convert it to a Number.

You should be able to simply do:

String code = itemMODEL.getCodiceArticolo());

No point in converting to a Number only for it to be made back into a String. You don't need a format either this way.

Upvotes: 1

Christopher
Christopher

Reputation: 10259

Your barcode is too big to fit into a 4-byte Integer. The max. positive range of an Integer is 2^31 - 1 = 2147483647. You should use Long instead:

String.format("%013d", Long.valueOf(itemMODEL.getCodiceArticolo()))

Upvotes: 1

Related Questions