java - Casting Large Numbers -



java - Casting Large Numbers -

import java.util.scanner; public class cast { public static void main(string[] args) { scanner scan = new scanner(system.in); double x = scan.nextdouble(); double x1 = (int) x; system.out.println(x); system.out.println(x1); } }

i'm working on simple bank business relationship program. it's working fine, when seek come in big number , cast it, code breaks down. isolated 1 section of code see if wrong code or whether else... wrote quick , found when entered big number like... 10000000000000000000 , casted integer, 2.147483647e9 result. figured issue casting.

why happen? what can prevent happening or else can in order resolve issue.

it expected result of downcasting int big number big fit in valid range of int. getting integer.max_value double.

section 5.1.3 of jls states:

a narrowing conversion of floating-point number integral type t takes 2 steps:

in first step, floating-point number converted either long, if t long, or int, if t byte, short, char, or int, follows:

if floating-point number nan (§4.2.3), result of first step of conversion int or long 0.

a. otherwise, if floating-point number not infinity, floating-point value rounded integer value v, rounding toward 0 using ieee 754 round-toward-zero mode (§4.2.3). there 2 cases:

b. if t long, , integer value can represented long, result of first step long value v.

otherwise, if integer value can represented int, result of first step int value v.

otherwise, 1 of next 2 cases must true:

a. value must little (a negative value of big magnitude or negative infinity), , result of first step smallest representable value of type int or long.

b. value must big (a positive value of big magnitude or positive infinity), , result of first step largest representable value of type int or long.

(emphasis mine)

if need value preserved, can seek casting long or using biginteger. if supposed represent money, utilize bigdecimal avoid floating-point representation , calculation issues.

java casting numbers

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -