[英]how to perform arithmetic operation to strings in java?
sorry for asking this simple question but i tried many ways still i am struggling to find solution. 很抱歉提出这个简单的问题,但我还是尝试了很多方法来解决问题。 i have a 2 string variable and i need to make addition operation for those string variable.
我有2个字符串变量,我需要对这些字符串变量进行加法运算。
I tried The following Code: 我尝试了以下代码:
String first="01.25";
String second="00.35";
Float f1=Float.parseFloat(first);
Float f2=Float.parseFloat(second);
Float f3=f1+f2;
System.out.println("value"+f3);
For Example: 例如:
String first="01.25"; 字符串first =“ 01.25”; String second="00.35";
字符串second =“ =” 0.0.35“;
Required answer is 01.60 必填答案是01.60
How can i achieve can any one help to fix this??? 我怎样才能解决这个问题?
Thanks in advance 提前致谢
Use following code: 使用以下代码:
String first="01.25";
String second="00.35";
Float f1=Float.parseFloat(first);
Float f2=Float.parseFloat(second);
Float f3=f1+f2;
String result=new DecimalFormat("00.00").format(f3);
System.out.println("value"+result);
Output : 输出:
value01.60
All you need is a DecimalFormat
to format your result to required pattern. 您只需要一个
DecimalFormat
即可将结果格式化为所需的模式。 For more on DecimalFormat
visit this link. 有关
DecimalFormat
更多信息,请访问此链接。
Use a DecimalFormat
object to format your number: 使用
DecimalFormat
对象格式化数字:
DecimalFormat numberFormat = new DecimalFormat();
numberFormat.setMinimumIntegerDigits(2);
numberFormat.setMinimumFractionDigits(2);
System.out.println(numberFormat.format(f3));
Or initialize the instance with a pattern. 或使用模式初始化实例。
DecimalFormat numberFormat = new DecimalFormat("00.00");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.