Archive

Posts Tagged ‘Java’

HowTo: round a number up to N decimal digits in Javascript

Was just trying to round-off some Google Maps coordinates for display in Javascript up to 3 decimal digits and that was a bit like a blast from the past (the end of the ‘90s to be more accurate)…

So here’s my contributed answer at:
https://stackoverflow.com/questions/2221167/javascript-formatting-a-rounded-number-to-n-decimals

This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):

function roundN(value, digits) {
   var tenToN = 10 ** digits;
   return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}

Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you’d end up with some unexpectedly long decimal part (this is due to floating point arithmetics).

A user comment at Format number to always show 2 decimal places calls this technique scaling.

Some mention there are cases that don’t round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:

function round(value, decimals) {
  return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

image

HowTo: Code folding in NetBeans IDE source code editor

As explained near the end of https://ui.netbeans.org/docs/ui/code_folding/cf_uispec.html, the NetBeans IDE source code editor supports custom code folding tags for any language, like below (here defining the code folding tag in a Java comment, obviously need to use specific comment syntax for the respective language).

// <editor-fold desc="isUserStudent"> —————————————-

public static boolean isUserStudent(PortletRequest request)
   throws NamingException, PortletServiceUnavailableException,  PumaException, SQLException
{
   return isUserStudent(new DbAccess().getConnection(), request);
}

public static boolean isUserStudent(Connection connection, PortletRequest request)
   throws NamingException, PortletServiceUnavailableException,  PumaException, SQLException
{
   return !StringUtils.isNotPresent(getUserStudentId(connection, request));
}
 
public static boolean isUserStudent(int studentId, PortletRequest request)
   throws NamingException, PortletServiceUnavailableException,  PumaException, SQLException
{
   return isUserStudent(studentId, new DbAccess().getConnection(), request);
}

public static boolean isUserStudent(int studentId, Connection connection, PortletRequest request)
   throws NamingException, PortletServiceUnavailableException,  PumaException, SQLException
{
   return (String.valueOf(studentId).equals(getUserStudentId(connection, request)));
}
 
public static String getUserStudentId(Connection connection, PortletRequest request)
   throws NamingException, PortletServiceUnavailableException,  PumaException, SQLException
{
   return DbStudent.getStudentId(connection, Puma.getUserName(request)); 
}

// </editor-fold>————————————————————-

 

This shows up in NetBeans like below when folded:

image

You can also optionally specify defaultstate="collapsed" at the code folding tag so that when the file is opened that region appears collapsed.

Categories: Posts Tags: , , , , , , ,

Gotcha: Java Calendar class returns 0-based month, but 1-based days

Just noticed that the Java Calendar class breaks the least-user-expected rule (that is don’t make something behave in the least expected way) regarding the indexing of the month value it returns, compared to all other indexed variables it can return (like day of year, day of month, day of week etc.). The former is using a 0-based index, whereas all the others are 1-based.
get
public int get(int field)
Returns the value of the given calendar field. In lenient mode, all calendar fields are normalized. In non-lenient mode, all calendar fields are validated and this method throws an exception if any calendar fields have out-of-range values. The normalization and validation are handled by the complete() method, which process is calendar system dependent.
Parameters:
field – the given calendar field.
Returns:
the value for the given calendar field.
MONTH
public static final int MONTH
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
DATE
public static final int DATE
Field number for get and set indicating the day of the month. This is a synonym for DAY_OF_MONTH. The first day of the month has value 1.
DAY_OF_MONTH
public static final int DAY_OF_MONTH
Field number for get and set indicating the day of the month. This is a synonym for DATE. The first day of the month has value 1.

There is an interesting discussion about this at
http://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar

At http://imagej.1557.x6.nabble.com/month-of-the-macro-function-quot-getDateAndTime-quot-td4999707.html one reads that this confusing setting came from UNIX (similar to those silly command abbreviations [“creat” instead of “create” etc.):

The origins lie with the POSIX

standard functions |ctime|, |gmtime| and |localtime|, which accept or

return a |time_t| structure with the following fields (from man 3 ctime

<http://linux.die.net/man/3/ctime>):

|int tm_mday;    /* day of month (1 – 31) */

int tm_mon;     /* month of year (0 – 11) */

int tm_year;    /* year – 1900 */

|

This API was copied pretty much exactly into the Java Date class in Java

1.0, and from there mostly intact into the Calendar class in Java 1.1.

Sun fixed the most glaring problem when they introduced Calendar – the

fact that the year 2001 in the Gregorian calendar was represented by the

value 101 in their Date class. But I’m not sure why they didn’t change

the day and month values to at least both be consistent in their

indexing, either from zero or one. This inconsistency and related

confusion still exists in Java (and C) to this day.”

Validating E-mails using Regular Expressions in Java

To sum up the discussion at http://stackoverflow.com/questions/1360113/is-java-regex-thread-safe/, you can reuse (keep in static variables) the compiled Pattern(s) and tell them to give you new Matchers when needed to validate those regex pattens against some string:


import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Validation helpers
 */ 
public final class Validators {  

  private static final String EMAIL_PATTERN = 
    "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*
     @[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
  
  private static Pattern email_pattern;  

  static {  
    email_pattern = Pattern.compile(EMAIL_PATTERN);
  }

  /**
   * Check if e-mail is valid 
   */   
  public static boolean isValidEmail(String email) {    
    Matcher matcher = email_pattern.matcher(email);
    return matcher.matches(); 
  }

}

(Note: the EMAIL_PATTERN string should be put in a single line)

For the RegEx pattern used, see the article at http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/ and the user comments (and useful links) posted there.

Update (20120715): previous pattern wasn’t accepting “-” in the domain name

Categories: Posts Tags: , , , ,
%d bloggers like this: