Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: double-to-int conversion without a cast Date: Fri, 3 Jun 2016 08:22:53 -0400 Organization: A noiseless patient Spider Lines: 43 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Fri, 3 Jun 2016 12:22:58 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="2d081e2f7155c28005d4472f67c2f43d"; logging-data="18784"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/WGXsLNBSACtEoai3Wf3FA" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Thunderbird/45.1.1 In-Reply-To: Cancel-Lock: sha1:Pr37xgJ1qD56Cu/3ynf8IF61low= Xref: csiph.com comp.lang.java.programmer:34453 On 6/3/2016 6:53 AM, Martin Gregorie wrote: > On Thu, 02 Jun 2016 22:18:13 -0700, Roedy Green wrote: > >> On 25 Feb 2016 01:07:44 GMT, ram@zedat.fu-berlin.de (Stefan Ram) >> wrote: >> >>> ouble to int >>> with only the above means >> >> I asked the conversion amanusensis at >> http://mindprod.com/applet/converter.html >> >> it offered: >> >> // to int i from double d // best i = (int)d; >> // or i = (int)Math.round(d); >> // or i = (int)Math.ceil(d); >> // or i = (int)Math.floor(d); > > This works: > > int n = new Long(Math.round(d)).intValue(); > > Look Ma, no casts! Too expensive -- just *look* at that wasteful creation of an object! Tut, tut, tut! Try this: int n = Integer.parseInt( Double.toString(d) .substring(0, Double.toString(d).indexOf('.'))) + (Double.toString(d).indexOf('.') >= 0 && Double.toString(d).indexOf('.') + 1 < Double.toString(d).length() && Double.toString(d).charAt( Double.toString(d).indexOf('.') + 1) >= '5' ? Double.toString(d).startsWith("-") ? -1 : 1 : 0); Look, Ma, no `new'! -- esosman@comcast-dot-net.invalid "Don't be afraid of work. Make work afraid of you." -- TLM