将字符串转换为Java中2位小数的十进制数 [英] Convert string to decimal number with 2 decimal places in Java

查看:675
本文介绍了将字符串转换为Java中2位小数的十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我试图将一个格式为###。##的字符串解析为一个浮点数。即使字符串的值 123.00 ,浮动也应该是2个小数位。 123.00 ,而不是 123.0



这是我到目前为止:

  System.out.println(字符串的汽油放入喜好是+ stringLitersOfPetrol); 

Float litersOfPetrol = Float.parseFloat(stringLitersOfPetrol);

DecimalFormat df = new DecimalFormat(0.00);
df.setMaximumFractionDigits(2);

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

System.out.println(放入编辑器前的汽油升数+ litersOfPetrol);

打印:

 在放入编辑器之前,汽油的字符串升为010.00 
升汽油:10.0


  litersOfPetrol = Float  

.parseFloat(df.format(litersOfPetrol));

在这里,您将float设置为字符串,但是随后该字符串再次转换为浮动,然后你在标准输出是你的浮法,得到了一个标准的格式。看看这段代码

  import java.text.DecimalFormat; 

String stringLitersOfPetrol =123.00;
System.out.println(字符串的汽油放入喜好是+ stringLitersOfPetrol);
Float litersOfPetrol = Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat(0.00);
df.setMaximumFractionDigits(2);
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println(放入编辑器之前的汽油升数+ stringLitersOfPetrol);

顺便说一下,当你想使用小数时,忘记double和float的存在建议只使用BigDecimal对象,它会为您节省很多头痛。


In Java, I am trying to parse a string of format "###.##" to a float. The string should always have 2 decimal places.

Even if the String has value 123.00, the float should also be 123.00, not 123.0.

This is what I have so far:

System.out.println("string liters of petrol putting in preferences is " + stringLitersOfPetrol);

Float litersOfPetrol = Float.parseFloat(stringLitersOfPetrol);

DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

System.out.println("liters of petrol before putting in editor: " + litersOfPetrol);

It prints:

string liters of petrol putting in preferences is 010.00 
liters of petrol before putting in editor: 10.0

解决方案

This line is your problem:

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

There you formatted your float to string as you wanted, but but then that string got transformed again to a float, and then what you printed in stdout was your float that got a standard formatting. Take a look at this code

import java.text.DecimalFormat;

String stringLitersOfPetrol = "123.00";
System.out.println("string liters of petrol putting in preferences is "+stringLitersOfPetrol);
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : "+stringLitersOfPetrol);

And by the way, when you want to use decimals, forget the existence of double and float as others suggested and just use BigDecimal object, it will save you a lot of headache.

这篇关于将字符串转换为Java中2位小数的十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆