TimeParser { public long parse() { if (time == null) { return 0; } final boolean isSeconds; if (time.endsWith("ms")) { isSeconds = false; } else if (time.endsWith("s")) { isSeconds = true; } else { return -1; } final String timeValue; final long factor; if (isSeconds) { timeValue = time.substring(0, time.length() - 1); factor = MSECS_PER_SEC; } else { timeValue = time.substring(0, time.length() - "ms".length()); factor = 1; } final BigDecimal number; try { number = new BigDecimal(timeValue); } catch (NumberFormatException e) { return -1; } float flt = number.floatValue(); return (long) (flt * factor); } TimeParser(final String str); long parse();  }
@Test public void testParse() { final TimeParser parser1 = new TimeParser("10s"); Assert.assertEquals(10000, parser1.parse()); final TimeParser parser2 = new TimeParser("2.7s"); Assert.assertEquals(2700, parser2.parse()); final TimeParser parser3 = new TimeParser(".5s"); Assert.assertEquals(500, parser3.parse()); final TimeParser parser4 = new TimeParser("850ms"); Assert.assertEquals(850, parser4.parse()); final TimeParser parser5 = new TimeParser("+1.5s"); Assert.assertEquals(1500, parser5.parse()); final TimeParser parser6 = new TimeParser("20"); Assert.assertEquals(-1, parser6.parse()); final TimeParser parser7 = new TimeParser("abcs"); Assert.assertEquals(-1, parser7.parse()); final TimeParser parser8 = new TimeParser(null); Assert.assertEquals(0, parser8.parse()); }