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);
Related
This question already has answers here:
Java keep trailing 0 in float operations
(3 answers)
Closed 4 years ago.
I have a requirement where I am getting a float value in java like the one below
1.1
1.10
10.10
when I convert this to string, I want it to be in the same way as
"1.1"
"1.10"
"10.10"
however, when I use the following method,
float fa = 25.50f;//Float.parseFloat("25.5");
String s = Float.toString(fa);
System.out.println(s); // i want the output to be 25.50, but it gives me 25.5
the result turns out to be the following
"1.1"
"1.1"
"10.1"
can somebody advise me how to get 1.10 as "1.10" with the zero in java
If you want it to store the whole number, why don't you just use a String?
I guess if you are getting "1.10" from somewhere, you are getting it as a String (or you would be getting just a "1.1").
There isn't (necessarily) a float value like 10.10f. There might be, but thing is: when you write down a float literal, you shouldn't expect that it really looks like the value you put down.
Only when representing numbers as strings you can uphold such requirements regarding formatting.
In other words, you probably should read this for example.
How it is printed is determined by how you format a number, the float is just a value, and it's actual representation is binary, not decimal.
String s = String.format("%.2f", 25.5f); // 25.50
I highly recommend using double which is simpler to use, and half a trillion times more accurate.
If your float value comes from String I suggest below solution:
public static void main(String[] args) {
String floatValue = "25.20";
String[] splittedFloat = floatValue.split("[.]");
int numberOfDecimalPlaces = splittedFloat[1].length();
float value = Float.valueOf(floatValue);
System.out.printf("%." + numberOfDecimalPlaces + "f\n", value);
}
First you declare your value as String. Then split it with "dot" and check the length of decimal places. Then you parse it into your float value and you do whatever you want with this value. And finally you cat print it with format like previous because you have number of decimal places of this float value.
The output of this code is:
25.20
There is no way to hold 25.20 value in float because the actual value is 25.2 and that 0 is formatting.
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
This question already has answers here:
Convert Double to Binary representation?
(7 answers)
Closed 7 years ago.
I want to create a binary represenation of a floating-point number and be able to parse that number back when needed. By "binary representation" I do not mean "0.00101" but something like "101000101", that is to say, a sequesnce of 0's and 1's with no decimal separator. I need a way to both create such representation in String for a double and to parse a double of a String.
Please do not mention the X Y problem because I do definitly need this method (something like "unsigned binary value").
Thank you in advance.
Convert Double to Binary representation? seemed to solve the problem with parsing double to String but I still need help with doing the opposite: from binary to double.
To convert the bits of a double to a String, you can use Double.doubleToLongBits, which creates a long with the same bits as the double, followed by Long.toBinaryString to convert it to a String with the bits as characters.
double test = 0.5;
long doubleBits = Double.doubleToLongBits(test);
String doubleBitsStr = Long.toBinaryString(doubleBits);
System.out.println(doubleBitsStr);
Output: 11111111100000000000000000000000000000000000000000000000000000
To convert back, use Long.parseLong with a radix of 2 and Double.longBitsToDouble.
doubleBits = Long.parseLong(doubleBitsStr, 2);
test = Double.longBitsToDouble(doubleBits);
System.out.println(test);
Output: 0.5
To convert the bits of a float to a String, you can use Float.floatTointBits, which creates an int with the same bits as the float, followed by Integer.toBinaryString to convert it to a String with the bits as characters.
float test2 = 0.5f;
int intBits = Float.floatToIntBits(test2);
String intBitsStr = Integer.toBinaryString(intBits);
System.out.println(intBitsStr);
Output: 111111000000000000000000000000
To convert back, use Integer.parseInt with a radix of 2 and Float.intBitsToFloat.
intBits = Integer.parseInt(intBitsStr, 2);
test2 = Float.intBitsToFloat(intBits);
System.out.println(test2);
Output: 0.5
Would Integer.toBinaryString(Float.floatToIntBits(yourNumber)); not work?
Strangest thing. I have this line
int i = Integer.parseInt("3",3);
But everytime i run it, i get a NumberFormatException.forInputString. Why? this is a simple base conversion. What is so special about the int 3 that breaks the conversion?
parseInt() expects a String as the first argument.
In base 3 there is no digit "3". Just "0" to "2". A decimal "3" is represented by "10" in base 3.
Integer.parseInt() expects a string to parse, not an integer. You want
int i = Integer.parseInt("3", 3);
You'll also run into the problem that 3 is not a digit in base three. As per the documentation, that will still throw a NumberFormatException.
Any character of the string is not a digit of the specified radix
If you want to parse base-10 to base-n String you can use something like :
System.out.println(Integer.toString(3, 2)); // print 11 -> String data type
Code above is to parse 3 in base 10 (integer) as binary (base-2) String.
Following code should parse base-2 String as base-10 integer value :
System.out.println(Integer.parseInt("11", 2)); // print 3 -> base-10 integer
Code above is to parse 11 binary to base-10 integer. Your code have error with this String format, for base-3 the string only consist 0, 1, 2.
Please note the difference how to use both method.
3 must be a numeric String to parse into an int rather than an int literal:
int i = Integer.parseInt("2", 3);
Furthermore, base-3 numbers cannot contain a 3 digit, as there's only 0, 1 and 2 available. Therefore I used 2 in the example code above.
3 simply does not exist as a digit in base 3...
0, 1, 2, 10, 11, 12, 20, 21, 22, 100
Integer.parseInt takes String as a signed decimal integer, and that integer must be less than and not equal radix value (base).
Integer.parseInt("X",x); //X mustn't contain x.
Why does this code sometimes return 1E+1 whilst for other inputs (e.g. 17) the output is not printed in scientific notation?
BigDecimal bigDecimal = BigDecimal.valueOf(doubleValue).multiply(BigDecimal.valueOf(100d)).stripTrailingZeros();
System.out.println("value: " + bigDecimal);
use bigDecimal.toPlainString():
BigDecimal bigDecimal = BigDecimal.valueOf(100000.0)
.multiply(BigDecimal.valueOf(100d))
.stripTrailingZeros();
System.out.println("plain : " + bigDecimal.toPlainString());
System.out.println("scientific : " + bigDecimal.toEngineeringString());
outputs:
plain : 10000000
scientific : 10E+6
It's the implicit .toString() conversion that is happening when you pass the result into System.out.println().
The exact rationale for the behaviour of BigDecimal.toString() is explained in the API doc in great (and near incomprehensible) detail.
To get a consistent (and locale-sensitive) textual representation, you should use DecimalFormat.
It's basically because you don't have enough significant digits. If you multiply something that only has 1 significant digit with 100, then you get something with only 1 significant digit. If it shows "10" then that basically says that it has 2 significant digits. The way to show it only has 1 significant digit is to show "1 x 10^1".
The following two decimals have the same value (10), but different "scales" (where they start counting significant digits; the top has 2 sig figs, the bottom has 1):
System.out.println(new BigDecimal(BigInteger.TEN, 0)); // prints 10
System.out.println(new BigDecimal(BigInteger.ONE, -1)); // prints 1E+1