I have a bean which has a property of type double. When I pass this bean to view layer, it shows the value in scientific notation For example: 9.78313E+10 instead of 97831300000.
I want the result without scientific notation and I cannot change the data type of that field. Please let me know if there is any workaround.
You can use the printf() with %f:
System.out.printf("%.0f", value);
Here you can find a beautiful printf format cheat sheet by Alvin Alexander that might help you (and hopefully others) a lot.
How the number is shown depends on the formatting that is used by the component showing the value. If you can't access that code to use a different formater; then there is nothing you can do.
See https://docs.oracle.com/javase/tutorial/java/data/numberformat.html for starters.
One option might be: can you exchange the bean implementation; so instead of providing a "double" number; can you change it to provide a string (in that case, you could control the formatting of the number).
I'm using java and Apache derby to create a project that deals with big numbers. Everything is going fine except when i store big numbers.
For eg. when i save 1000000000 through my java class to a derby table, it automatically becomes 1.0E9. When this value is retrieved in another form it is displayed like 1.0E9. How can I stop this? I'm using float data type to do this.
In other words, how can I save 1000000000 as 1000000000 and not 1.0E9
Like above said you could use a BigInteger or you could just covert 1.0E9 to what the number actually is. 1.0 x 10^9.
1.0e9 is the same as 1000000000; it's just a representation issue. You just have to apply the proper formatters when transforming it to a string.
Two things that would make this easier are to use the NUMERIC column type in Derby, and also use either BigDecimal or BigInteger data types in your Java code, or possibly a long if you're confident that the long can hold the values in your problem domain.
import java.math.BigInteger;
//...
//...
//...
BigInteger store = new BigInteger("1000000000");
This is basically what I am trying to do
// ... some code, calculations, what have you ...
long timeToAdd = returnTimeToAddInLongFormat();
// lets output the long type now, and yes i need the width and precision.
System.out.printf("Time to add: %13.10ld", timeToAdd);
I've read most of the google searches around the topic and think I understand how to do it conceptually, but the JRE keeps throwing me a UnknownFormatConversionException and telling me my input size modifier l doesnt work.
Is there another way to do this, or did I miss something small?
Java treats all integer values as d, there is no ld. Even byte and BigInteger is a d type. It also assumes integers have no decimal places. If you want to show 10 zeros, you can convert to double first and use f
I just bumped into this little problem and I wanted the input of other people on this
I was wandering what was the best solution to convert a String to an int
(int)(float)Float.valueOf(s)
or
Float.valueOf(s).toInt()
s is a String inputed from a textfield so I can not guarantee that it is necessarily an int
my instincts is that the double cast is ugly and should be avoided
Your input?
Your requirements are unclear:
If you are expecting an integer and don't want to allow the user to enter a number with a decimal point in it, simply use Integer.valueOf(String) or Integer.parseInt(String) and catch the NumberFormatException.
If you want to allow numbers with decimal points, then use Float.valueOf(String) or Float.parseFloat(String).
If you simply want to truncate the float to an int then either Float.intValue() or two casts are equivalent. (The javadoc for intValue explicitly states this.)
If you want to round to the nearest int, use Math.round() instead of a cast.
You should catch NumberFormatException whatever approach you take, since the user could enter rubbish that is not a valid base-10 number (with or without a decimal point) ... or that exceeds the bounds of the number type.
(I suppose that you could use a regex or something to check the String before trying to convert it, but it is simpler to just let the exception happen and deal with it. The exception efficiency issue is unlikely to be a practical concern in this use-case.)
On your original question as to whether intValue() is better than two casts: it is a matter of style. The two approaches do the same thing ... according to the javadoc. It is possible that one will be slightly more efficient than the other, but:
that shouldn't be a concern for your use-case, and
the only way to know for sure would be to profile the two alternatives on your execution platform ... and frankly it is not worth the effort.
You should use Integer.valueOf(..), and catch the NumberFormatException (if the string cannot be parsed as an integer).
Integer.parseInt(string) would be best
int x = Integer.parseInt(s);
Would be best to check if the string is an int before calling this.
As others pointed out, its just matter of style not performance... but if you are worried about performance you should validate the text field data in browser itself by javascript using a regex
^[0-9]*$
which would allow only integers to be submitted to your back-end code and hence improving performance by avoiding one network trip. Still you should validate the data in back-end, for that you can use
Integer.parseInt(String s) throws NumberFormatException
what type could contain a number like 2023209999 in java?
do you think that using a string type to represent a telephone number is a good idea?
Using a string is a very good idea. Remember that the point of OOP is that different types of data have different usage patterns. So let's look at a phone number patterns.
Do we add phone numbers or perform other arithmetic on them?
Do we split it based on length, match against parts of it, replace parts of it?
The answer to the first question is no. So we don't manipulate them like numbers. The answer to the second question is yes, so we manipulate them like strings.
Now, many here are advocating making phones a class by itself. There is merit in this regard, but I'm addressing the more pressing concern of how do you store the phone number, which is something you need to do no matter if a phone is a class or not. A phone class which stored its data as a number would not be a good fit.
I would write a PhoneNumber class, which uses String as an underlying storage, and adds validation / pretty formatting functionality.
I'd say a String at the least, but personally, I'd make a PhoneNumber object. It's the sort of thing that affords itself to extra methods such as:
boolean isValid();
PhoneNumberUtils.getCountry(PhoneNumber number);
PhoneNumberUtils.getState(PhoneNumber number);
...or whatever. One thing I'd be thinking out for is just letting people put in phone numbers and getting the system to learn the rest. I despise entering data that could be determined by the system. This is just my preference.
On a simpler level, just encapsulating the String in an PhoneNumber object gives your brain a handle ... in a week or so when your brain wonders "Where should this phone number method go?", you may find yourself with a quick answer.
I think that a dedicated PhoneNumber class is the way to go about it. Phone number are not just strings. First and foremost, phone numbers obey to rules, such as: they only contain digits, in the US they can contain either 7 or 10 digits. You'd need a constructor to make sure that your phone numbers are correct.
Second, a class will make it easy for you to steamline the differences between various formats. For instance, 555-4834 and 5554834 are different strings but are the same phone number.
Finally, you'd probably want methods such as: getAreaCode() or getLocalNumber() Calling such a method is much more concise and much less error prone than manipulating a String directly:
String phoneNumber pn = ....;
String localNumber = pn.length() == 7 ? pn : pn.substring(4) :
it's rather late, but I may add my 2 cents ....
I am in telecom and have made best experience to store phone numbers in structures (or objects) with character members of variable length, i.e.
struct TelephoneNumber (
InternationalPrefix VARCHAR;
AreaCode VARCHAR;
Subscriber VARCHAR;
Extension VARCHAR;)
I never store access digits (the zero's, double zeros, pluses etc.), they don't belong to to the telephone number per se but are part of what I may call "dialing rules"
struct DialingRule (
International VARCHAR;
National VARCHAR;
Local VARCHAR;)
typical values for DialingRule are "00", "0", NULL for a direct line, and "000", "00", "0" for a PBX requiring a "0 to get the line"
to "display" a number you can freely format the objects, insert hyphens, brackets or whatever you fancy
to create a dialable sequence I determine the type (international, national or local) by comparing the corresponding elements of the FROM and TO number and add the respective string from the dialing rule set as a prefix.
This all may sound like an overkill, but for international applications with strong requirements on data integrity and with strong links to hardware I didn't come up with any better. It removes ambiguities and the need for hardcoding lenghts etc. when you want to manipulate numbers. It's also easy to prefill parts of the structure from country / city lookup tables containing ISO country codes, IATA city codes and their corresponding prefixes.
Good luck
MikeD
In Germany area codes start with a 0 so a integer representation would lose that information.
Still I wouldn't recommend just using a String.
Instead use a Phonenumber class (or interface and implementations). This approach has some advantages.
If at some point you find that a String is insufficient you just have to change the Phonenumber class not every class that uses Phonenumbers.
Additionally it would allow you to seperate area code and number internally.
If you need to record leading 0 or + for international then you should use a String.
If you ain't worried about these you can just use a long. e.g.
long phoneNumber = 2023209999L; // the L is for a long constant.
It would honestly come down to what you plan to do with it. If you just want to store it to reprint it a string or maybe even a long would be fine, assuming we are dealing with US numbers.
If you want to do something more sophisticated making a Class with containing several strings, one for each component.
Basically just not enough info here to make a real decision.
Using a String Type allows you to break apart the phone number without any voodoo or casting.
For instance, if you change the format of how you accept phone numbers, you'll have to do extra work to get the phone number contatenated if it is a long instead of a string.
Another thing to consider: an int would be too small. the maximum value an int can hold is 2,147,483,647. as far as primitives are concerned, long is your best bet.
It depends on what you're doing. Let's say you want to be able to represent international numbers, local numbers, branch exchange numbers, etc. In this case, a String is a bad choice. It doesn't have any meta-information. You probably want a class to represent a phone number.
As far as what you use to represent the phone number in this class, you could use a BigInteger (to allow you to have international numbers), or more simply, you could store each portion of a phone number as a long.