开发者

formatting and converting in java

I have few small basic pr开发者_StackOverflow社区oblems :

How to format :

int i = 456;

to give output :

""00000456"

? I've tried %08d but it's not working. Next thing is a problem with conversion and then formatting. I have side and height of triangle, let's say int's 4,7, and 7 is the height. From formula for field we know that F=1/2(a*h). So how to get F as float, with precision up to 10 places ?

float f = a*h;

works fine, but multiplying it by 0.5 gives error and by 1/2 returns 0.


Use NumberFormat class see this or that explanation, the Formatter class or String.format


How to format :

int i = 456; to give output :

"00000456"

System.out.printf("%08d", i) can do the job.


1/2 is an integer expression, it will not be automatically converted to a float.

1/2 should be one of: 1.0f/2.0f, 1.0f/2, 1/2.0f, (float)1/(float)2, (float)1/2, 1/(float)2, float-variable/float-variable, float-variable/int-variable, int-variable/float-variable, ... you get the idea


Should be %.08d instead of %08d, secondly try multiplying by 0.5f instead.


Answer was to use String.format.

    String fs = String.format("%08d", this.id);
    return fs;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜