I have been working on localisation for my app and cant seem to find any information about how to handle decimal values and dates from different locals to store in sqllite.
for example:
German decimal 123,53
Uk decimal 123.53
So how do you convert from an edittext field to a valid decimal. At the moment I have my code outputting to a textview rather than sql just for testing. The below code works great when using UK decimal but if I use the german decimal it fails!!
Configuration sysConfig = getResources().getConfiguration();
Locale curLocale = sysConfig.locale;
NumberFormat nf = NumberFormat.getInstance(curLocale);
String convertedString = nf.format(Double.parseDouble(EditTextField.getText().toString()));
TextView showLocalisedNumeric;
showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
showLocalisedNumeric.setText(convertedString);
I have not started with dates yet but I am assuming converting dates for is more straight forward.
After some time working on this I found the solution for localisation, taking a value from input and parsing it to a format that can be understood by SQLlite - For this exercise and to reduce code I have just set it to output to a text view.
// set initial value to variables
String convertedString = "";
double parsedValue = 0.0;
//get value from text field
EditText EditTextField =(EditText)findViewById(R.id.TestNumericValueEntered);
String valueFromInput = EditTextField.getText().toString();
//Get current Locale from system
Configuration sysConfig = getResources().getConfiguration();
Locale curLocale = sysConfig.locale;
//Set number formats
NumberFormat nf_in = NumberFormat.getNumberInstance(curLocale);
NumberFormat nf_out = NumberFormat.getNumberInstance(Locale.UK);
//try to parse value, otherwise return error message
try {
parsedValue = nf_in.parse(valueFromInput).doubleValue();
// use nf_out.setMaximumFractionDigits(3) to set max number of digits allowed after decimal;
convertedString = nf_out.format(parsedValue);
}catch(ParseException e){
convertedString = "Unable to translate value";
}
//Output result
TextView showLocalisedNumeric;
showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
showLocalisedNumeric.setText(convertedString);
As I was adding this answer I realised that a nice addition to the code would be to check if the current locale is the same as the one you plan to parse to, if so then the conversion(parsing) can be skipped.
Related
I get information about timezone in such string format.
(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius
Is it somehow possible to parse it into some TimeZone object in Java with standard library or external one?
Depending how you want to use the TimeZone afterwards you might either create a custom one
String input = "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius";
// assuming the format is always fixed at the beginning
String timeZoneOffset = input.substring(4,10);
TimeZone timeZone = TimeZone.getTimeZone("GMT" + timeZoneOffset);
System.out.println("timeZone = " + timeZone);
output (line wrapped)
timeZone = sun.util.calendar.ZoneInfo[id="GMT+02:00",offset=7200000,dstSavings=0,\
useDaylight=false,transitions=0,lastRule=null]
You might get into trouble related to the daytime savings.
Or you create a lookup map with an entry for each offset (stripped down code snipped)
String input = "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius";
// assuming the format is always fixed at the beginning
String timeZoneOffset = input.substring(4,10);
// needs to be initialized somewhere
Map<String, TimeZone> timeZones = new HashMap<>();
// you need to add all offsets
timeZones.put("+02:00", TimeZone.getTimeZone("EET"));
System.out.println("timeZone lookup = " + timeZones.get(timeZoneOffset));
output (line wrapped)
timeZone lookup = sun.util.calendar.ZoneInfo[id="EET",offset=7200000,dstSavings=3600000,\
useDaylight=true,transitions=123,lastRule=java.util.SimpleTimeZone[id=EET,offset=7200000,\
dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,\
startDay=-,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,\
endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
I have to get value from a DB2 database and put it in a .txt file.
The value of a column is 0.0000
but in the .txt file it is coming as 0E-4.
When I take the value from the database, I put it in String datatype and then write it into a file.
How do i print 0.0000 in my .txt file?
Use DecimalFormat
Example :
double value = 123456789.6666;
System.out.println(value);
DecimalFormat formatter_1 = new DecimalFormat("#,###.0000");
String stValue = formatter_1.format(value);
System.out.println(stValue);
DecimalFormat formatter_2 = new DecimalFormat("###.0000");
stValue = formatter_2.format(value);
System.out.println(stValue);
Output :
1.234567896666E8
123,456,789.6666
123456789.6666
If price_from_db column declared as decimal(0,4), if there is no value in the database, it will consider 0.0000 by default.
Bigdecimal price;
if this value comes from DB as exponetial format say 0E-11
we can use price.toPlainString() in our java code to get the value like 0.00000000000
Worked for me !!
I use java 1.7.25
but found this error. what should I do?
FATAL EXCEPTION: main
java.lang.IllegalArgumentException: Unknown pattern character 'u'
at java.text.SimpleDateFormat.validateFormat(SimpleDateFormat.java:264)
at java.text.SimpleDateFormat.validatePattern(SimpleDateFormat.java:319)
at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:365)
at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:249)
Here is my code
public static int getDayNumberOfWeek(int day, String monthString, int yyyy) {
//http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
int dayNumberOfWeek = 1;
final String inputFormat = "MMM/dd/yyyy";
final String outputFormat = "u";
String dayString2Digit = DateTimeHelper.getTwoDigit(day);
String inputTimeStamp = monthString + "/" + dayString2Digit + "/" + String.valueOf(yyyy);
try {
dayNumberOfWeek =Integer.valueOf(TimeStampConverter(inputFormat, inputTimeStamp,
outputFormat));
}
catch (ParseException e) {
e.printStackTrace();
}
return dayNumberOfWeek;
}
I use java 1.7.25
No, you don't - not if you're running on Android. You need to look at the Android documentation, not the Java 7 docs.
If you look at the Android SimpleDateFormat documentation you'll see that u isn't listed there. I don't believe there's a format pattern character for "day of week as a number" in Android.
Were you really looking for that though? If you just want the day of the week as a number (without anything else) you can always use
String text = String.valueOf(calendar.get(Calendar.DAY_OF_WEEK));
If you're using android, then you're not using Java 1.7.25. See the android documentation: there's no support for u in SimpleDateFormat.
I'm guessing your problem is going to be in your TimeStampConverter class where you're passing in that "u" as the outputFormat. "u" is not a valid format character in SimpleDateFormat and you must be constructing a format string that contains it.
If you need to use the "u" as a literal, you'll need to enclose it in single quotes.
I have a TextView which display currencies. By default my textview's text is: $0.00
How can I make it so the $ changes based on user selection.
I have the following code:
Locale locale=new Locale("en", "US");
Currency currency=Currency.getInstance(locale);
String symbol = currency.getSymbol();
Toast.makeText(getActivity(), symbol, Toast.LENGTH_SHORT).show();
Which shows $ but if I have the following:
Locale locale=new Locale("en", "AU");
Currency currency=Currency.getInstance(locale);
String symbol = currency.getSymbol();
Toast.makeText(getActivity(), symbol, Toast.LENGTH_SHORT).show();
it shows AU$ instead of $
How can I set the currency symbol without all the extra stuff?
If what you want is to add that format to a number you have you could do
myString = NumberFormat.getCurrencyInstance().format(myNumber);
for default
or
myString = NumberFormat.getCurrencyInstance(new Locale("en", "AU")).format(myNumber);
for specified
You could use a regular expression to remove all word characters.
String symbol = currency.getSymbol().replaceAll("\\w", "");
However this may not be ideal if any of the monetary symbols you are dealing with use letters.
I am getting a phone number from one excel file and write into another excel file using the following code
cellph = row.getCell(3);
Object phone = cellph.getNumericCellValue();
String strphone = phone.toString();
cellfour.setCellType(cellfour.CELL_TYPE_STRING);
cellfour.setCellValue("0"+strphone);
It writes the phone number as 09.8546586. I want to write it as 098546586(without precision value). How to do that?
Your problem isn't with the write. Your problem is with the read, that's what's giving you the floating point number
From your code and description, it looks like your phone numbers are stored in Excel as number cells, with an integer format applied to it. That means that when you retrieve the cell, you'll get a double number, and a cell format that tells you how to format it like Excel does.
I think what you probably want to do is something more like:
DataFormatter formatter = new DataFormatter();
cellph = row.getCell(3);
String strphone = "(none available)";
if (cellph.getCellType() == Cell.CELL_TYPE_NUMERIC) {
// Number with a format
strphone = "0" + formatter.formatCellValue(cellph);
}
if (cellph.getCellType() == Cell.CELL_TYPE_STRING) {
// String, eg they typed ' before the number
strphone = "0" + cellph.getStringCellValue();
}
// For all other types, we'll show the none available message
cellfour.setCellType(cellfour.CELL_TYPE_STRING);
cellfour.setCellValue(strphone);