开发者

problem with integers

can anybody开发者_JAVA技巧 look at this code and tell me why the exception happens?

public static void main(String[] args)
{
    int total =100;
    int discount_Ammount = 20 ;
       int newAccount=Integer.parseInt( String.valueOf(Math.floor(total - discount_Ammount)).trim());
}

Method floor returns double value , then I make casting to integer, so I cast it to string then to integer... please, can anybody help?


You aren't "casting" anything. trim() removes whitespace only, which will never be present in the result of String.valueOf(double).

Use a cast:

int newAccount = (int) Math.floor(total - discount_Ammount);

Java is a strongly typed programming language, not a scripting language. Implicit conversions between strings and other types are not supported.

Or, get rid of the floor() operation altogether, since you are working with an int quantity already, and floor() is meaningless:

int newAccount = total - discount_Ammount;

If you are working with money, use the BigDecimal class so that you can use the round-off rules required by your accounting system. You won't have control of that when using double.


Did you try this?

int newAccount = (int) Math.floor(total - discount_Ammount);

Or even this!

int newAccount = total - discount_Ammount;


No need to do Integer.parseInt( String.valueOf(

To cast to int, just do (int)(blah)

So int newAccount=(int)(Math.floor(total - discount_Ammount));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜