What is the difference between these 2 String formatting? - java

value
double value = 345.12345;
String Format 1
String str = String.format("%.02f", value);
String Format 2
String str = String.format("%.2f", value);
Both print the same value 345.12. So, what is the difference between these two?

The 0 prefix notation only works for the integer part, not the decimal part. If you had say %07.2f instead, it would show the value as 0345.12.

The syntax for a format specifier is
%[argument_index$][flags][width][.precision]conversion
Note that precision is 02 in the first case and 2 in the second case, but since these are the same number, the output is the same. Hence "%.02f" and "%.2f" are the same.
But, if you had written %02f, then flags would be 0 ("zero-pad output up to width") and width would be 2. Then the output would be zero-padded up to the specified width.

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);

One "0" is missing in my binary - how can I fix it? [duplicate]

This question already has answers here:
How to convert a long to a fixed-length 16-bit binary string?
(8 answers)
Closed 5 years ago.
I tried to encrypt with the OTP (One Time Pad). I have coded a "test"-code to see if I make everything right, or not.
final String message = "Hello";
char character;
String binary;
for (int i = 0; i < message.length(); i++) {
character = message.charAt(i);
binary = Integer.toBinaryString(character);
System.out.println(character + ": " + binary);
}
So, there are the following:
H: 1001000
e: 1100101
l: 1101100
l: 1101100
o: 1101111
That is not really correct. I've searched in the inet, for example, the binary of H
01001000
There is one "0" missing. How can i fix this?
Instead of binary = Integer.toBinaryString(character);
use the following expression:
binary = String.format("%8s", Integer.toBinaryString(character)).replace(' ', '0');
The missing zeroes are leading zeroes. A binary representation is numerical in essence, which means leading zeroes have no meaning. Therefore they are left out; the number 01001000 equals the number 1001000.
If you do want to print these leading zeroes, I suggest you solve this by using a string formatting function, that prints an exact number of digits regardless of the number's length.
Another option would be using the DecimalFormat:
private static String format( Integer value, String format )
{
DecimalFormat myFormatter = new DecimalFormat( format );
return myFormatter.format( value );
}
With this you can just reach in the Number and the format in which it should be displayed. Like this:
System.out.println(format( 1001000 , "00000000" ));
With 0 as format you say the number 0 has to displayed or the number that is reached in. Meaning if your format is longer than the actual number the leading places will be displayed as 0.
If you read the JavaDoc you will find the section
Special Pattern Characters
There you can see an overview of the options for your format and what they will do.
EDIT:
As Olivier pointed out in the comments it is needed to convert it again.
When you convert your Character with Integer.toBinaryString(character);
you can just cast the String back to Long with Long.valueOf() and then reach it into to function or just refactor the method to:
private static String format( String value, String format )
{
DecimalFormat myFormatter = new DecimalFormat( format );
return myFormatter.format( Long.valueOf(value) );
}

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.

Fromatting double value to 2 decimals

i want to format my double value to 2 decimals and then make it "text to speech".
this is my code:
mares = mass * acc;
DecimalFormat df = new DecimalFormat("#.00");
df.format(mares);
String mare = String.format("The force is %f", df);
home.speak(mare,TextToSpeech.QUEUE_FLUSH, null);
but it crashes, i don't know why, i put 5 and 6 and it should multiply them and give me 30.00 or something like that.
when i remove DecimalFormat the result is 30.00000000000000, i just don't like it, too many zeros.
can someone help me please?
Thanks in advance!
Your DecimalFormat is returning the formatted string, but you are ignoring it, and passing it as an argument to String.format, which certainly isn't right.
Assign the return of df.format to a string for further reference:
String mare = df.format(mares);
Or pass the numeric value directly to String.format, with the appropriate format precision specified:
String mare = String.format("The force is %.2f", mares);

Java: string tokenizer and assign to 2 variables?

Let's say I have a time hh:mm (eg. 11:22) and I want to use a string tokenizer to split. However, after it's split I am able to get for example: 11 and next line 22. But how do I assign 11 to a variable name "hour" and another variable name "min"?
Also another question. How do I round up a number? Even if it's 2.1 I want it to round up to 3?
Have a look at Split a string using String.split()
Spmething like
String s[] = "11:22".split(":");;
String s1 = s[0];
String s2 = s[1];
And ceil for rounding up
Find ceiling value of a number using Math.ceil
Rounding a number up isn't too hard. First you need to determine whether it's a whole number or not, by comparing it cast as both an int and a double. If they don't match, the number is not whole, so you can add 1 to the int value to round it up.
// num is type double, but will work with floats too
if ((int)num != (double)num) {
int roundedNum = (int)num + 1;
}

Categories

Resources