Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

Convert a number to 2 decimal places in Java

I want to convert a number to a 2 decimal places (Always show two decimal places) in runtime. I tried some code but it only does, as shown below

 20.03034 >> 20.03
 20.3 >> 20.3  ( my code only rounds not converts )

however, I want it to do this:

 20.03034 >> 20.03
 20.3 >> 20.30 (convert it to two decimal places)

My code below:

angle = a variable
angle_screen =  a variable

DecimalFormat df = new DecimalFormat("#.##");
angle = Double.valueOf(df.format(angle));
angle_screen.setText(String.valueOf(angle) + tmp);

Any help on how to do this would be great, thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this new DecimalFormat("#.00");

update:

    double angle = 20.3034;

    DecimalFormat df = new DecimalFormat("#.00");
    String angleFormated = df.format(angle);
    System.out.println(angleFormated); //output 20.30

Your code wasn't using the decimalformat correctly

The 0 in the pattern means an obligatory digit, the # means optional digit.

update 2: check bellow answer

If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...