DecimalFormat pattern - java

public static String formatAmountUpToTwoDecimalNumber(String amount)
{
if(amount==null || "".equals(amount))
{
return "";
}
Double doubleAmount = Double.valueOf(amount);
double myAmount = doubleAmount.doubleValue();
NumberFormat f = new DecimalFormat("###,###,###,###,##0.00");
String s = f.format(myAmount);
return s;
}
"###,###,###,###,##0.00", What exactly is the purpose of this pattern ? I believe it serves two purposes
to group numbers, that is put thousand seperator comma
to append two zeros after decimal if decimal is missing that is convert 23 to 23.00
But why there is "0" instead of "#" before decimal? what exactly is the purpose of this zero?
Thanks for the help.

Symbol Location Localized? Meaning
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
From: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
So # is not shown when there is no number. The leading 0 means there will be at least 1 digit before the decimal separator.

# will put a digit only if it is not a leading zero. 0 will put a digit even if it is a trailing zero. You could use zeros in front, too, if you wanted a fixed number of digits printed.

With the zero before the dp, small numbers like 0.23 will be displayed as 0.23. Without it you will not get the leading zero, so it is just displayed as .23. If you have a spreadsheet like excel you can check this there too.

Related

How to print entire number even after removing decimal point?

I have a number as
Double d = 100.000000;
I want to remove the decimal point and print the values as 100000000
(Note I am using java)
It is impossible. double doesn't store zeroes after decimal point so 1.0000 is equal to 1.0.
Hint: you can use BigDecimal for this. It have scale.
I'm afraid 100.000000 does not equal 100000000 and as mentioned by #talex, double doesn't store the zeros after the decimal point.
Your best bet is to use a String and remove the . manually:
String s = "100.000000";
System.out.println(s.replaceAll("\\.", "")); //note '.' needs to be escaped
Output:
100000000
You could parse it as a Double then if necessary.
Format the value using String.format and the remove the separator.
double d = 100.000;
String formatted = String.format(
Locale.US, //Using a Locale US to be sure the decimal separator is a "."
"%5f", //A decimal value with 5decimal
d) //The value to format
.replace(".", ""); //remove the separator
System.out.println(formatted);
100000000
Other examples :
100.000123456 > 100000123
You can see that the value is truncated, it is important to understand that.
Note that I have set the String to have 5 decimal number, but this up to you.
the double does not store the number as 100.0000 it just stored as 100.0 that means any unnecessary zeros on the right will be deleted but if the number was like this 100.01234 u can use this trick
Double d = 100.01245;
String text = Double.toString(d);
text.replace(".","");
d = Double.parseDouble(text);
or u can store the number as sting from the beginning
String text = "100.000000";
d.replace(".","");
double d = Double.parseDouble(text);

Regular Expression Matching for number only with 2 digits repeated

I am trying to match number which are having 2 digits and those are repeated and the length of number is 7 digits .
I want to match these numbers from java .
example numbers:
3433434
6776767
9000999
Please help to create the regular expression for these pattern numbers
I'd recommend hiding any regexes inside helper methods:
private static boolean matchesCriteria(String s) {
return exactlySevenDigits(s) && containsRepeatedDigits(s);
}
private static boolean exactlySevenDigits(String s) {
return s.matches("\\d{7}");
}
private static boolean containsRepeatedDigits(String s) {
return s.matches(".*(\\d)\\1.*");
}
Example results:
3433434 true
6776767 true
9000999 true
1234567 false (no repeating numbers)
12331233 false (too long)
123356A false (not all digits)
You can do it as follows:
String str = "3433434";
boolean sevenOf2Digits = str.length() == 7 &&
str.matches("(\\d)\\1*+(\\d)(\\1|\\2)*");
System.out.println(sevenOf2Digits);
The first (\\d) captures the first digit in group 1.
\\1 is a backreference to group 1, so the first digit. * is 0 or more of those digits, + makes that possessive, which is required to prevent the next (\\d) from matching the same digit.
The following (\\d) captures the second digit in group 2.
(\\1|\\2)* just matches 0 or more of any combination of the first or second digits.
I separated out the length check for simplicity. If you want a pure regex solution, you can add the length check to your regex in the form of a lookahead by adding (?=.{7}$) to the start of your regex.
"(?=.{7}$)(\\d)\\1*+(\\d)(\\1|\\2)*"
With regex it is a little complicated, I would use this way (Java 8+) instead :
boolean check = myString.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.toSet())
.size() == 2;
The idea is to create a Set with the character of this string, if the size of the Set is 2 then it is correct String else it is not.
Or as Ralf Renz mention in comment, you can use this short way :
boolean check = myString.chars().distinct().count() == 2;
So your final solution should look like this :
boolean check = myString.matches("\\d{7}") && myString.chars().distinct().count() == 2;
(?=^.{7}$)(\d)\1*(?!\1)(\d)(?:\1|\2)*
This should do it. It finds a digit and repeats, then finds a second digit and repeats. Then it checks if the rest of the number is one of those 2.
I'll explain in detail what this does.
(?=^.{7}$): Before starting, make sure there are 7 characters between the start and end. If shorter or longer, fast fails.
(\d)\1*(?!\1)(\d): Get the first digit and save it in a capture group. Then matches if the captured digit is also the next one. If there is only a single digit, the next part will catch that. Last digit should always be different then the first one.
(?:\1|\2): repeat the 2 captured digits 0 or more times.
String regex = "[10]{7}|[20]{7}|[21]{7}|[30]{7}|[31]{7}|[32]{7}|[40]{7}|[41]{7}|[42]{7}|[43]{7}|[50]{7}|[51]{7}|[52]{7}|[53]{7}|[54]{7}|[60]{7}|[61]{7}|[62]{7}|[63]{7}|[64]{7}|[65]{7}|[70]{7}|[71]{7}|[72]{7}|[73]{7}|[74]{7}|[75]{7}|[76]{7}|[80]{7}|[81]{7}|[82]{7}|[83]{7}|[84]{7}|[85]{7}|[86]{7}|[87]{7}|[90]{7}|[91]{7}|[92]{7}|[93]{7}|[94]{7}|[95]{7}|[96]{7}|[97]{7}|[98]{7}";
System.out.println(Pattern.matches(regex, "3433434"));
System.out.println(Pattern.matches(regex, "6776767"));
System.out.println(Pattern.matches(regex, "9000999"));
That should do it. All combinations of two digits with a length of 7.

Convert float to string and always get specific length of string?

How can I convert a float to a String and always get a resulting string of a specified length?
For example, if I have
float f = 0.023f;
and I want a 6 character string, I'd like to get 0.0230. But if I want to convert it to a 4 character string the result should be 0.02. Also, the value -13.459 limited to 5 characters should return -13.4, and to 10 characters -13.459000.
Here's what I'm using right now, but there's gotta be much prettier ways of doing this...
s = String.valueOf(f);
s = s.substring(0, Math.min(strLength, s.length()));
if( s.length() < strLength )
s = String.format("%1$-" + (strLength-s.length()) + "s", s);
From java.util.Formatter documentaion: you can use g modifier, precision field to limit number to specific number of characters and width field for padding it to column width.
String.format("%1$8.5g", 1000.4213);
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
Though precision doesn't include dot and exponent length – only digits in mantissa counted.
By keeping extra place for dot and cutting extra digits from fractional part if string is significantly wider that could be solved too.
String num = String.format("%1$ .5g", input);
if (num.length > 6)
num = num.substring(0, 2) + num.substring(7); //100300 => ' 1e+05'; 512.334 => ' 512.33'
Scientific format of number always follows strict set of rules, so we don't have to search for dot inside string to cut fraction out of string if sign is always included (or, like in case above – replaced by space character for positive numbers).

Number of digits after decimal using String.format

I know to convert a double value to string , I can do like this :
String value = String.format("%f", 10.0000);
Also I can control the number of digits after decimal using this :
String value = String.format("%.3f", 10.000000);
But my problem is that, I am receiving number of digits after decimal point through a variable.
How can I use String.format to print the number of digits after decimal provided by the user.
Regards,
Anuj
String value = String.format("%."+x+"f", 10.000000);
where x is number of digits.

How to make 0 display as 0.00 using decimal format?

I am using the following code to make numbers display with two decimal places and thousands comma separator.
public static String formatNumber(double amount){
DecimalFormat formatter = new DecimalFormat("#,###.00");
return formatter.format(amount);
}
For other numbers it is ok but 0 is returned as ".00" I want it to be "0.00" What should I change?
The # means optional digit, so if you use 0 instead it will work:
DecimalFormat formatter = new DecimalFormat("#,##0.00");
BTW: I think you need 3 ### not 4.
Why not
return String.format("%.2f", amount);
That would format it correctly wouldn't it? (if amount is 123123.14233 then it would return 123123.14)
or
return String.format("%,.2f", amount);
for commas within the number. (if amount is 123123.14233 then it would return 123,123.14)

Categories

Resources