I am not experienced in Java at all and am using a text editor to write code so I can't see what the problem is (I am running from command line)
I see the error and know what it is but I have no idea how to fix it
System.out.print(String.format("%7d", Math.pow(n,2).toString()));
I also tried without the .toString()
Basically if I print only n it works, but the power function gives me an error probably because of return types, but pow should return a double and the string format %7d is probably also double right?
You are using wrong format specifier.. %d is used for integer.
Math.pow() returns primitive double on which you cannot invoke toString() method.
Try using %7s which is for String, and convert your primitive double value to Wrapper type: -
String.format("%7s", Double.valueOf(Math.pow(n,2)).toString())
But, you don't need to convert your argument to String, you can directly use double value with %f: -
String.format("%.3f", Math.pow(n,2));
You most likely want to use f instead of d without the toString. If you actually were able to do toString (as Quoi points out, you cannot do from a primitive), it would make it impossible to use Formatters that expect the used Number object (Double in your case).
This is the Formatter that String.format uses.
problem lies with toString method. You have given format specifier %7d that means integer. You can't print string in place of it.
The Right Format for double is %f not %d so modify your code to:
System.out.print(String.format("%7f", Math.pow(n,2)));
see also :link
Math#pow(double,double) returns primitive double value you can not call toString method.
Use f instead of d, and d is for a decimal integer.
System.out.format("%7f", Math.pow(n,2));
Better start with Eclipse or any other editor to write code.
Related
I need to convert Byte to KB.So i divide the value by 1024
I need to display the value in this format specified originally in Java Number formatting ###,###,###,##0.00 KB
This code
string format="###,###,###,##0.00 KB";
return String.Format(format, x);
produces the following output
###,###,###,##0.00 KB
This formatting string is specified in the Java counterpart,wont the same approach work in C#?
Please advice.
String.Format and IFormattable.ToString (the formatting you need here) are different, yet related things.
String.Format requires some format string with placeholders and the substituted values can also have formatting if they implement the IFormattable interface.
Console.WriteLine(String.Format("{0} KB", 42.ToString("###,###,###,##0.00")));
The formatting of 42 can be inlined:
Console.WriteLine(String.Format("{0:###,###,###,##0.00} KB", 42));
Which can be simplified further by interpoation:
Console.WriteLine($"{42:###,###,###,##0.00} KB"));
Of course, 42 can be a variable in the interpolation ($"{numValue:###,###,###,##0.00} KB}"). However, the format string cannot be a variable, so this will not work:
string format = "{x} KB";
Console.WriteLine($format); // does not compile, use String.Format in this case
Remark:
Console.WriteLine also supports formatting so the examples above could have been written like this:
Console.WriteLine("{0:###,###,###,##0.00} KB", 42);
I used explicit String.Format just to avoid confusion.
Update
If the size formatting comes from an external source you cannot inline it into the format string but this is not a problem. So if you have
string fileSizeFormat = "###,###,###,##0.00 KB";
You can still use myFloatWithFileSize.ToString(fileSizeFormat). In this case String.Format is needed only if you want to embed this into a nice sentence or something:
return String.Format("The size of the file: {0}", fileSize.ToString(fileSizeFormat));
or with interpolation:
return $"The size of the file: {fileSize.ToString(fileSizeFormat)}";
hi i am trying to print after dividing in string builder and printing that string builder let show me my code ,
string.append("Memomry usage:total:"+totalMemory/1024/1024+
"Mb-used:"+usageMemory/1024/1024+
" Mb("+Percentage+"%)-free:"+freeMemory/1024/1024+
" Mb("+Percentagefree+"%)");
in above code "totalmemory" and "freememory" is of double type having bytes value in point not null so i divide it by "1024" two times to get it in "Mb" and "string" is variable of string builder after using this code i am simply printing it a am getting result as shown below,
Used Memory:Memomry usage:
total:13.3125Mb-used:0.22920989990234375Mb (0.017217645063086855%)
-free:13.083290100097656Mb (0.9827823549369131%)
i want to get percentage in twodecimal place and values of used and free memory in mb like this "used:2345.25" in this pattren remember
Hopes for your suggestions
Thanks in Advance
How about String.format()?
System.out.println(String.format("output: %.2f", 123.456));
Output:
output: 123.46
Try like this
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Using DecimalFormat, we can format the way we wanted to see.
You can use DecimalFormat to print out to two decimal places. So, to print x = 2345.2512 with two decimal places, you would write
NumberFormat f = new DecimalFormat("#.00");
System.out.println(f.format(x));
which will print 2345.25.
Even though it is possible to use NumberFormat and it's subclass DecimalFormat for this issue,
these classes provide a lot of functionality that may not be required for your application.
If the objective is just pretty printing, I would recommend using the format function of the String class. For your specific code it would look like this:
string.append(String.format("Memomry usage:total:%1.2f Mb-used:%1.2f Mb(%1.2f %%)-free:%1.2f Mb(%1.2f %%)",totalMemory/1024/1024,usageMemory/1024/1024,Percentage,freeMemory/1024/1024,Percentagefree));
If you are intending to specify a standard format in which all numbers are represented irrespective of whether they are being parsed from strings or formatted to strings, then I would recommend using singletons of the *Format classes. They allow you to use standard formats and also to pass format descriptions between methods.
Hope that helps you select the right method to use in your application.
Hello and thank you in advance for the help.
I am having some trouble formatting using a Java function to mark up a price in HTML.
It seems that, no matter what I do, I cannot insert custom content between the numbers and the decimal (throws Illegal Argument Exception). Is there any known way to achieve the following:
NumberFormat nf = getNumberFormat("'<span class=\"dollars\">'##'</span></span class=\"decimal\">'.'</span></span class=\"cents\">'00'</span>'", locale);
nf.format(number);
Assume locale and number are correctly initialized.
If you look at the docs for DecimalFormat you'll see that they talk about the prefix and the suffix text - but not putting arbitrary text within a number.
It sounds like you should basically write this bit of formatting yourself - possibly using DecimalFormat for each section of the number.
You might consider using String.format(String pattern, Object... arguments). You can pass your simply formatted numbers as arguments.
In my web application I have a version field that take float input values. But when using values like 1000000.1 (or larger) for the version it displays like 1.0E7. i tried several methods in Float wrapper class. but result still the same.
Thanks
Your problem is not in parsing but in formatting of your values. The value is correct and it is represented in java correctly. If you wish to change the format user either String.format() that provides C style formatting or java.text.NumberFormat.
System.out.printf("%f", Float.parseFloat("1.0E7")); outputs 10000000.000000
See http://ideone.com/3o6dO
Note that 1.0E7 is 1000000.0, not 1000000.1.
it probably has to do with your output format because 1.0E7 == 10000000
I think what you are looking for is the String.format(locale, msg, args) method.
Use String.valueOf(floatNumber)
Suggest use double instead of float
I've been reading up on the net about the issues with handling float and double types in java. Unfortunately, the image is still not clear. Hence, i'm asking here direct. :(
My MySQL table has various DECIMAL(m,d) columns. The m may range from 5 to 30. d stays a constant at 2.
Question 1.
What equivalent data-type should i be using in Java to work (i.e store, retrieve, and process) with the size of the values in my table? (I've settled with double - hence this post).
Question 2.
While trying to parse a double from a string, i'm getting errors
Double dpu = new Double(dpuField.getText());
for example -
"1" -> java.lang.NumberFormatException: empty String
"10" -> 1.0
"101" -> 10.0
"101." -> 101.0
"101.1" -> 101.0
"101.19" -> 101.1
What am i doing wrong? What is the correct way to convert a string to a double value?
And what measures should i take to perform operations on such values?
EDIT
This is the code -
System.out.println(dpuField.getText());
Double dpu = new Double(dpuField.getText());
System.out.println(dpu);
Yes, the problem lies with getText() reporting the wrong value of the dpuField.
This method is called on the JTextField keyTyped event. So what's going wrong here?
EDIT 2
Looking at :
http://journals.ecs.soton.ac.uk/java/tutorial/post1.0/ui/keylistener.html
Apparently, keyTyped() does not give me the keycode. I'll have to switch to keyRealeased()
What equivalent data-type should i be using in Java to work (i.e store, retrieve, and process) with the size of the values in my table? (I've settled with double - hence this post).
Since it's a DECIMAL field, you should prefer java.math.BigDecimal. You can store it in DB using PreparedStatement#setBigDecimal() and you can retrieve it from DB using ResultSet#getBigDecimal().
While trying to parse a double from a string, i'm getting errors
This can't be true. The problem lies somewhere else. Maybe it is just not returning the data you expect to be returned or you are not using/debugging the values you expect them to be.
if you need exact precision without rounding errors, you should use a BigDecimal.
Your code looks OK - could it be that dpuField.getText() somehow cuts the last character from the string values you list above?
Update: you say
Yes, the problem lies with getText() reporting the wrong value of the dpuField. This method is called on the JTextField keyTyped event.
Could it be that getText() returns the value of the field before the last typed key is actually appended to it?
For decimal, I believe you risk losing precision if you don't use a BigDecimal on the Java side, as some decimal fractions can't be stored as a binary fraction.
Prefer Double.valueOf(String) over the constructor, but that's a valid way. Something else must be going on (i.e. I doubt those are the actual String values you're passing in).
Question1: It's bad idea to map DECIMAL columns to Double, usually the BigDecimal is the correct type. http://java.sun.com/j2se/1.3/docs/guide/jdbc/getstart/mapping.html#1055175
Question 2: You are doing something wrong; print the String value before converting.