Issue
Simple questions as a beginner making big problems.
I want to shorten (format) a String to only show 1 decimal or 2. Unlucky it is a String not a double.
String getNumber = "6.000m";
I know there is a printf() function but as far I learned it is to print multiple string in a proper order.
How can I make the output to be with only one decimal or if it has more numbers which aren't 0?
6.000 m --> 6.0
4.900 m --> 4.9
4.750 m --> 4.75
Solution
I assume it is always "m" at the end with some optional whitespace in front of it. So I remove it first using a regex. DecimalFormat is your friend to do the rest:
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Ff {
static Pattern numberPart=Pattern.compile("([0-9.]*)\\b*m");
static DecimalFormat df=new DecimalFormat("0.0#####");
public static String format(String input)
{
Matcher m=numberPart.matcher(input);
if(m.matches())
{
return df.format(Double.parseDouble(m.group(1)));
}
return null;
}
public static void main(String args[]) {
System.out.println(format("6.000m"));
System.out.println(format("4.900m"));
System.out.println(format("4.750m"));
}
}
and the output is:
6.0
4.9
4.75
Answered By - Conffusion Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.