How to format 18 digit double to become 10 string character - java

double pdouble= 3.3603335204002837E12;
String pstart= Double.toString(pdouble).replace(".", "") .trim()
String.format("%10d", pstart);
System.out.println("pstart"+pstart);
Can I know why it not works...
It display this:
Exception in thread "main"
java.util.IllegalFormatConversionException: d != java.lang.String at
java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
.I
Hope anybody can help

%d is for int. As pstart is a String, Use b or s.
String.format("%10s", pstart);
Output
33603335204002837E12
Read Java String format()
However if you need only the first 10 digits from your number, try using DecimalFormat
DecimalFormat d = new DecimalFormat("0000000000");
String number = d.format(pdouble);
Output
3360333520400
This will also add leading 0s if the number is less than 10 digits.

For decimal numbers "f" flag needs to be used.
double pdouble= 3.3603335204002837E12;
System.out.println(String.format("%10f", pdouble));
This will print a string with minimum length of 10 chars.
In this pattern "%10f" the width flag (e.g. 10) is the minimum number of characters
The width is the minimum number of characters to be written to the output. For the line separator conversion, width is not applicable; if it is provided, an exception will be thrown.
from Formatter java doc

Related

Java Format string to C#

Don't understand Java's syntax. How to convert: "%6d %7.1f %5.1f" to C# equivalent ?
I keep getting this print out in C#: %6d %7.1f %5.1f
Tried:
"{0:d6} {7:1f} {5:1f}"
But, ran into an exception.
Exception:
Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(String format, Object arg0, Object arg1, Object arg2)
at experiment.Main(String[] args)
The Java code:
String.format("%6d %7.1f %5.1f", int, double, double/double);
It's obvious what values will be generated based on variable data types.
EDIT: I just looked at, Convert this line of Java code to C# code
C#
String.Format("{0:x2}", arrayOfByte[i]);
Java
String.format("%02x", arrayOfByte[i]);
PLEASE. PLEASE. PLEASE. DO not close this. Kindly. Please.
NOTE: Completely rewrote my original answer based on a (hopefully) better understanding of the Java format specifiers.
Based on my (Google-limited understanding), %6d, %7.1f and %5.1f correspond to the following:
An integer with up to 6 characters, padded if less than 6.
A float with up to 7 characters (including the decimal point and decimal portion) with a precision of 1.
A float with up to 5 characters (including the decimal point and decimal portion) with a precision of 1.
You can accomplish this with C#'s String.Format, like this:
var newString = String.Format("{0,6:d} {1,7:f1}, {2,5:f1}", 605, 20.5, 8.22);
This will result in the following string:
" 605 20.5 8.22"
The first digit in each placeholder group (defined by { and }) corresponds to the argument passed in after the string:
0 = 605
1 = 20.5
2 = 8.22
The second digit, after the , refers to the length of the string (including decimal points and decimal portions).
6 = 6 characters for the integer
7 = 7 characters for the float
5 = 5 characters for the float
The letters and numbers after the : are the format specifiers.
d = integer
f1 = floating with a precision of 1.
Which produces the string above, as follows:
{0,6:d} turns 605 into " 605" (3 leading spaces due to the 6 before the :)
{1,7:f1} turns 20.5 into " 20.5" (3 leading spaces due to the 7 before the :)
{2,5:f1} turns 8.22 into " 8.2" (1 leading space due to the 5 before the : and 1 decimal number due to the precision).
As I said earlier, check String.Format and Standard Numeric Format Strings for more information.
Starting from C# 6. you can use interpolation.
For your case you may wanted to try the following:
string formattedString = $"{0:d6} {7.1:f} {5.1:f}";
before C# 6 you can try the following:
string formattedString = String.Format("{0:d6} {1:f} {2:f}", 0, 7.1, 5.1);

System.out.printf("%-15s%03d%n", s1, x) How to interpret it

In each line of output there should be two columns:
The first column contains the String and is left justified using exactly 15 characters.
The second column contains the integer, expressed in exactly 3 digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.
can someone explain the System.out.printf("%-15s%03d%n", s1, x);
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++)
{
String s1=sc.next();
int x=sc.nextInt();
System.out.printf("%-15s%03d%n", s1, x);
}
System.out.println("================================");
}
}
Basically every %... is gonna be replaced by one of the arguments of printf. What is after the % sign is a format specifier.
In %-15s:
- means: left-justified
15 means: if the result is less than 15 characters long, add spaces until it is 15 characters long
s means: convert the parameter into a string with toString and use the result
In %03d:
0 means: pad with 0s instead of spaces
3 means: make it at least 3 characters long
d means: the argument will be an integer number, format it as a base-10 number.
%n is the same as \n on *NIX or \r\n on Windows.
You will get more info here: https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
EDIT based on remarks by AxelH and Andy Turner
Its Java formatter syntax
first half - %-15s
% - says that what follows is an argument that will be formatted.
s - says youre formatting a string
15 - number of characters you put into string
and finally - means string is gonna be justified to the left
second half - %03d
d means youll be adding integers
0 means youll be adding 0's where necessary
3 means you need to add 3 digits
%n is System.line_separator - basically outputs new line. It does the same as /n but %n is portable across platforms (credit #AxelH)

How to print formatted double value to string in java?

I want to create a String from a double value with 10 character for example
Double d = 150.23;
The output string like this 0000015023+
I have used this code but it is not working:
String imponibile = String.format("%10d%n", myDoubleValue);
You want to print 150.23 without the period. Formatting is not supposed to achieve that. You have to:
transform the double number to a int number with the desired rounding and print the int:
int i = (int) Math.round(100.0 * d);
String.format("%010d", i)
Where "010" means print at least 10 digits and pad with zero if there are less. The padding char going before the number of digits.
print the double and remove the period from the string afterwards:
String.format("%011.2f", d).replace(".", "")
Note how you now have to specify 11 including the period. And you have to specify the number of digits after the period
I don't think there is a way to print the sign after a number with String.format. You can easily require to print it at the start which is the normal way to print numbers:
String s = String.format("%+010d", i);
And if you must you can use substring and concatenation to put it at the end:
String imponibile = s.substring(1) + s.charAt(0);
Try f instead of d:
String imponibile = String.format("%010.0f", myDoubleValue*100);
Floating Point - may be applied to Java floating-point types: float,
Float, double, Double, and BigDecimal
Class Formatter

how to add digits in a long variable that will be converted to string?

i had this method:
public long getLastSequenceNumber();
it should return me:
0
a number that should be like 34,60,103...
the maximum amount of 12 digits number (243265438564 for example).
What i want is when i get this number i want to convert it to a String and add the "0" that is missing in the front of number to get the 12 digits. if it comes with 12 digits then just convert to string.
Example:
if i get 45 then convert to "000000000045".
if i get 0 then convert to "000000000000".
if i get 834213238956l (12 digits) then just convert to
"834213238956" (same number, but in String).
How i can do it in Java?
You can use a DecimalFormat to convert the number directly to a String.
DecimalFormat df = new DecimalFormat("000000000000"); // 12 zeros
String s = df.format(x);
String fortyFive = df.format(45);
Alternatively, you can call String.format with a 0 to indicate leading zeros and a 12 for the length.
String s = String.format("%012d", x);
String fortyFive = String.format("%012d", 45);

Arbitrary radix padded format

I wonder if there's a standard way in Java to format an integer number into an arbitrary radix with left-padded zeroes.
E.g. for radix-32, padded to 4 characters length, if I have a number 30, I'd like to get a string like "000t" or if I have 300 I should get "008z" (t and 8z not necessarily correspond to base-32 notation of 30 and 300, it's just an example).
Convert the integer to a string in the radix that you need, then use the string formatter to pad the output string. The string formatter will pad with spaces, which you then need to convert to zeros.
Here's an example:
int num = 300;
String numString = Integer.toString(num, 30);
String padded = String.format("%1$#4s", numString).replace(' ', '0'); // "00ao"
The second argument to toString is the radix: 30 in this case.
The first argument to String.format is the format string, which I took from here. The value you care most about is the 4 in the middle of string: that's the total number of characters that you want in the string.

Categories