简体   繁体   English

使用DecimalFormat方法

[英]Using the DecimalFormat method

  1. Display y to three decimal places 显示y到小数点后三位
  2. Display how many digits come before the decimal point and how many comes after a number. 显示小数点前有几位数,数字后有几位数。 On x , y and z xyz
  3. Create a string E that consists of D in reverse concatenated with F , including a space between them 创建一个字符串E ,该字符串由DF反向串联而成,其中D之间包含一个空格
  4. Search for the substring 'i' in c and replace it for 'fff' c搜索子字符串'i'并将其替换为'fff'

x = 123.456, y = 54/5, z = √2, D = “Decimal”, F = “Function” x = 123.456,y = 54/5,z =√2,D =“十进制”,F =“函数”

I did this for question 1 and it works but I am not sure if this is how I am suppose to do this and I have not clue how to go about doing question 2,3 and 4. Any help would be appreciated. 我是针对问题1这样做的,但它确实有效,但是我不确定这是否是我应该做的方式,并且我不知道如何进行问题2,3和4。任何帮助将不胜感激。

double y = 54.0/5.0;
DecimalFormat y_format = new DecimalFormat("#.###"); 
String formatted_string1 = y_format.format(y);
System.out.println(formatted_string1);

For 2, you can divide the number by 10 until it reaches 0. A simple counter with a while loop would work well. 对于2,您可以将数字除以10,直到达到0。带有while循环的简单计数器会很好地工作。 You could so similar for the other case. 对于其他情况,您可能是如此相似。 (using multiplication) (使用乘法)

For 3, Simply use a loop to read a character at a time from D and concatenate to a new String. 对于3,只需使用循环即可一次从D读取一个字符并将其连接到新的String。

for ( i from D.length to 0)
  newString += D.charAt(i)
newString += F

For 4, check the replace method in String. 对于4,检查String中的replace方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM