Locale currency = new Locale("ms-my");
//Locale of Malaysia
if (!editable.toString().equals(current)) {
TransferAmount.removeTextChangedListener(this);
String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance(currency)
.getCurrencyInstance().getCurrency().getSymbol());
String cleanString = editable.toString().replaceAll(replaceable, "");
double parsed;
try {
parsed = Double.parseDouble(cleanString);
} catch (NumberFormatException e) {
parsed = 0.00;
}
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setMaximumFractionDigits(0);
String formatted = formatter.format((parsed));
current = formatted;
TransferAmount.setSelection(formatted.length());
TransferAmount.addTextChangedListener(this);
}
I would like to set the Currency as Malaysia and the Malaysia Country Code is "ms-my". I would like to add Malaysia currency symbol in front of the text. Is there anyway?
Simple solution would be add the Malaysia Country Code "ms-my" like a prefix
EditText editable = (EditText)findViewById(Your_id);
editable.addTextChangedListener(currencyFormatWatcher);
private final TextWatcher currencyFormatWatcher = new TextWatcher() {
String prefix = "ms-my "; //"MYR "
Locale currency = new Locale("ms-my");
public void afterTextChanged(Editable s) {
if(!s.toString().equals("")){
editable.removeTextChangedListener(this);
String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance(currency)
.getCurrencyInstance().getCurrency().getSymbol());
String cleanString = editable.toString().replace(prefix, "").replaceAll(replaceable, "");
double parsed;
try {
parsed = Double.parseDouble(cleanString);
} catch (NumberFormatException e) {
parsed = 0.00;
}
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setMaximumFractionDigits(0);
String formatted = formatter.format((parsed));
formatted = prefix.concat(formatted);
editable.setText(formatted);
editable.setSelection(formatted.length());
editable.addTextChangedListener(this);
}
}
};
Check this answers
Related
I have below Java code to convert string format to Timestamp object
public class TestUtil{
Object result;
Public Object convertFormat(String format, String value, String type){
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date = dformat.parse(value);
result = new Timestamp(date.getTime);
System.out.println("Result::"+ result);
}
}
Expected outcome:
I was expecting the outcome should be like below
20050225144824
Actual outcome:
2005-02-25 14:48:24.0
Could anyone tell me what I am missing here? To get "20050225144824" this result
The below code runs fine for me.
Adding few print statements to explain the different behaviors.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
public class Main
{
public static void main(String[] args) {
String myFormat = "yyyyMMddHHmmss";
String value = "20050225144824";
try {
SimpleDateFormat dformat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = dformat.parse(value);
Timestamp ts = new Timestamp(date.getTime());
Object result = new Timestamp(date.getTime());
System.out.println("Timestamp Format with yyyyMMddHHmmss : " +dformat.format(ts));
System.out.println("Object Format with yyyyMMddHHmmss : " +result);
System.out.println("Object Format with yyyyMMddHHmmss : " +dformat.format(result));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Here is the output of the different behaviors :
Timestamp Format with yyyyMMddHHmmss : 20050225144824
Object Format with yyyyMMddHHmmss : 2005-02-25 14:48:24.0
Object Format with yyyyMMddHHmmss : 20050225144824
If you expect Timestamp to return your custom output then you need to override the default Timestamp library.
Here I create CustomTimestamp.java to extend Timestamp and override its toString() method. I modified the changes according to your requirement.
public class CustomTimestamp extends Timestamp {
private int nanos;
public CustomTimestamp(long time) {
super(time);
}
#Override
public String toString () {
int year = super.getYear() + 1900;
int month = super.getMonth() + 1;
int day = super.getDate();
int hour = super.getHours();
int minute = super.getMinutes();
int second = super.getSeconds();
String yearString;
String monthString;
String dayString;
String hourString;
String minuteString;
String secondString;
String nanosString;
String zeros = "000000000";
String yearZeros = "0000";
StringBuffer timestampBuf;
if (year < 1000) {
// Add leading zeros
yearString = "" + year;
yearString = yearZeros.substring(0, (4-yearString.length())) +
yearString;
} else {
yearString = "" + year;
}
if (month < 10) {
monthString = "0" + month;
} else {
monthString = Integer.toString(month);
}
if (day < 10) {
dayString = "0" + day;
} else {
dayString = Integer.toString(day);
}
if (hour < 10) {
hourString = "0" + hour;
} else {
hourString = Integer.toString(hour);
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = Integer.toString(minute);
}
if (second < 10) {
secondString = "0" + second;
} else {
secondString = Integer.toString(second);
}
if (nanos == 0) {
nanosString = "";
} else {
nanosString = Integer.toString(nanos);
// Add leading zeros
nanosString = zeros.substring(0, (9-nanosString.length())) +
nanosString;
// Truncate trailing zeros
char[] nanosChar = new char[nanosString.length()];
nanosString.getChars(0, nanosString.length(), nanosChar, 0);
int truncIndex = 8;
while (nanosChar[truncIndex] == '0') {
truncIndex--;
}
nanosString = new String(nanosChar, 0, truncIndex + 1);
}
// do a string buffer here instead.
timestampBuf = new StringBuffer(20+nanosString.length());
timestampBuf.append(yearString);
timestampBuf.append(monthString);
timestampBuf.append(dayString);
timestampBuf.append(hourString);
timestampBuf.append(minuteString);
timestampBuf.append(secondString);
timestampBuf.append(nanosString);
return (timestampBuf.toString());
}
}
Your main class should use CustomTimestamp to get the output
try {
String format = "yyyyMMddHHmmss";
String value = "20050225144824";
SimpleDateFormat dformat = new SimpleDateFormat(format);
java.util.Date date;
date = dformat.parse(value);
Timestamp result = new CustomTimestamp(date.getTime());
System.out.println("Result::" + result);
} catch (ParseException e) {
e.printStackTrace();
}
im new to Java and JavaFX and I want to create a GUI with a Label which shows the current system Time.
The Problem is: the Time Value doesn't update. So I wanted to create a Thread, that is updating my Time-Value and also the Label every 1 second with the command:
label_time_show.setText(curTime);
In the inizialize method (see code below) the "label_show_time" can be inizialized with any value, but when I try to setText in an other method I get the following Error:
Exception in thread "Thread-4" java.lang.NullPointerException
I commented the line in the Code where the Label is null and where the Label is NOT null.
Can someone help me with this Problem?
public class FXMLDocumentController implements Initializable, Runnable
{
public String curTime; // <--- main value of time (String)
#FXML
private Label label_time_show;
#FXML
private Label label_time;
// initializer
#Override
public void initialize(URL url, ResourceBundle rb)
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
label_show_time.setText(curTime); // <---- label_show_time is NOT null
}
// run method
#Override
public void run()
{
System.out.println("THREAD FXMLController running....");
while(true)
{
time();
}
}
public void time()
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
label_show_time.setText(curTime); // <---- label_show_time is null !!! throws ERROR
}
}
So, given the limited information, I'll take a blind stab at this. At the end of your initialize method your label is not null, so start your thread then.
public void initialize(URL url, ResourceBundle rb)
{
//java.util.Date now = new java.util.Date();
//Long sysTime = now.getTime();
//String sysTimeString = sysTime.toString();
//Integer h = now.getHours();
//Integer m = now.getMinutes();
//Integer s = now.getSeconds();
//String hh = h.toString();
//String mm = m.toString();
//String ss = s.toString();
//curTime = hh + ":" + mm + ":" + ss;
//label_show_time.setText(curTime); // <---- label_show_time is NOT null
//Since the label not null here, start your thread here.
new Thread(this).start();
}
Then your time method would be similar except you would post things to the Platform thread.
public void time()
{
java.util.Date now = new java.util.Date();
Long sysTime = now.getTime();
String sysTimeString = sysTime.toString();
Integer h = now.getHours();
Integer m = now.getMinutes();
Integer s = now.getSeconds();
String hh = h.toString();
String mm = m.toString();
String ss = s.toString();
curTime = hh + ":" + mm + ":" + ss;
Platform.runLater(()->{
label_show_time.setText(curTime);
});
}
You might want to put a sleep in your run method since you only need to update every second.
public void run(){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
while (true){
Date date = new Date();
label_show_time.setText(dateFormat.format(date));
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException e){
}
}
}
mb it helps you?
and init your label.
update:
public void initialize(URL url, ResourceBundle rb) {
...
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
new Thread(new Runnable() {
#Override
public void run() {
while (true){
Date date = new Date();
System.out.println(dateFormat.format(date));
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException e){
}
}
}
}).start();
}
I want to write a java method that takes a string in input and outputs another string following this rule:
input output
"123456" "12:34:56"
"23456" "02:34:56"
"3456" "00:34:56"
"456" "00:04:56"
"6" "00:00:06"
Any help would be appreciated. Thanks.
I would advice to use DateFormat as below. This will take care of all the burdens of conversion.
DateFormat formatFrom = new SimpleDateFormat("HHmmss");
DateFormat formatTo = new SimpleDateFormat("HH:mm:ss");
String origTimeString = "456";
String newDateString = null;
try {
String formattedString =
String.format("%06d", Integer.parseInt(origTimeString));
Date date = formatFrom.parse(formattedString);
newDateString = formatTo.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Updated string : " + newDateString);
Copy this method and use it.
1) If string length is more than 6, it's going to return "ERROR".
2) First fixes the String with '0'
3) Second fixes the String with ':'
4) StringBuilder is used for concat. Avoid using '+' operator for concat.
5) Method 'getDate' is static because of 'main' method is static, too.
public static String getDate(String variable){
StringBuilder aux= new StringBuilder();
StringBuilder string= new StringBuilder();
int length = variable.length();
if(length>6 || length<=0){
return "ERROR";
}else{
//first to fill blanks with 0
for(int i=0;i<6-length;i++){
aux.append("0");
}
variable = aux.append(variable).toString();
//second to put :
for(int i=0;i<6;i++){
if(i%2==0 && i!=0){
string.append(":");
}
string.append(variable.charAt(i));
}
return string.toString();
}
}
public static void main(String[] args) {
System.out.print(getDate("464"));
}
I am learning BigDecimal and i want it to retrieve the exact number i entered, the following code is rouding the number and i dont know why
public static BigDecimal parseFromNumberString(String numberString) {
if (numberString != null) {
String nonSpacedString =
numberString.replaceAll("[ \\t\\n\\x0B\\f\\r]", "").replaceAll("%", "");
int indexOfComma = nonSpacedString.indexOf(',');
int indexOfDot = nonSpacedString.indexOf('.');
NumberFormat format = null;
if (indexOfComma < indexOfDot) {
nonSpacedString = nonSpacedString.replaceAll("[,]", "");
format = new DecimalFormat("##.#");
} else if (indexOfComma > indexOfDot) {
nonSpacedString = nonSpacedString.replaceAll("[.]", "");
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
otherSymbols.setDecimalSeparator(',');
format = new DecimalFormat("##,#", otherSymbols);
} else {
format = new DecimalFormat();
}
try {
return new BigDecimal(format.parse(nonSpacedString).doubleValue(), new MathContext(12));
} catch (ParseException e) {
// unrecognized number format
return null;
}
}
return null;
}
If i do something like
public static void main(String[] args){
BigDecimal d = Test.parseFromNumberString("0.39");
System.out.println(d);
}
The value printed is 0,00 and not 0.39
Try this code:
public static BigDecimal parseFromNumberString(String numberString) {
if (numberString != null) {
String nonSpacedString =
numberString.replaceAll("[ \\t\\n\\x0B\\f\\r]", "").replaceAll("%", "");
int indexOfComma = nonSpacedString.indexOf(',');
int indexOfDot = nonSpacedString.indexOf('.');
DecimalFormat decimalFormat = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
String pattern = "#0.0#";
if (indexOfComma < indexOfDot) {
symbols.setDecimalSeparator('.');
} else if (indexOfComma > indexOfDot) {
symbols.setDecimalSeparator(',');
}
try {
decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
BigDecimal toRet = (BigDecimal) decimalFormat.parse(nonSpacedString);
return toRet.setScale(12);
} catch (ParseException e) {
return null;
}
}
return null;
}
public static void main(String... args) {
BigDecimal d = Test.parseFromNumberString("0,39");
System.out.println(d);
}
Is that what you want??
i just ran your code and i get. 0.390000000000 maybe you forgot to save?
try cleanning your project, restart your ide and recompile. the code should work fine
In my java program a java variable String inputDate accepts input form user. I want to enforce users to enter date in (dd/MM/yyyy) format only as my other modules depend on that format only. Here's what I tried so far:
public class InputQuery {
private static String FLIGHT_DATE;
public String getFLIGHT_DATE() {
return FLIGHT_DATE;
}
public void setFLIGHT_DATE() {
boolean invalid = true;
Scanner sc = null;
while(invalid){
System.out.println("Enter FLIGHT_DATE(dd/MM/yyy) :");
sc = new Scanner(System.in);
FLIGHT_DATE = sc.nextLine();
if( (invalid = isValidDate(FLIGHT_DATE)) ) {
System.out.println("For Feb 21,2016 enter 21/02/2016");
}
}
sc.close();
}
private boolean isValidDate(String flight_DATE) {
SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
if( flightDate.parse(flight_DATE)){
System.out.println("accepted OK");
return true;
}
return false;
}
Use myDateFormat.setLenient(false).
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
try{
sdf.parse(incomingDateString);
// if you get here, the incomingDateString is valid
}catch(ParseException ex){
// if you get here, the incomingDateString is invalid
}
This won't work, try this
private boolean isValidDate(String flightDate) {
SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
myDateFormat.setLenient(false);
try {
myDateFormat.parse(flightDate);
} catch (ParseException e) {
return false;
}
System.out.println("accepted OK");
return true;
}
You can use regex to check given input is in format or not try this:
public class DateValidator {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String flightDate = null;
boolean isDateValid = false;
while(!isDateValid){
System.out.print("Enter FLIGHT_DATE(dd/MM/yyy) :");
flightDate = scanner.nextLine().trim();
isDateValid = isDateValid(flightDate);
if(!isDateValid){
System.out.println("Wrong Format.");
}
}
System.out.println("continue.");
}
public static boolean isDateValid(String flightDate){
String regex = "^\\d{2}/\\d{2}/\\d{4}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(flightDate);
return matcher.find();
}
}
To my understanding, what you'd like to do is to ensure that the date entered corresponds to the format.
The parse(String) method doesn't return a boolean, and it never returns null. If it's successful, it returns a date; if it's unsuccessful, it throws an exception. The way to do this is:
private boolean isValidDate(String flight_DATE) {
SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
myDateFormat.parse(flight_DATE);
return true;
} catch (ParseException ex) {
// You may want to print the exception here, or do something else with it
return false;
}
}