Skip to content

Commit

Permalink
simplify padding with formula
Browse files Browse the repository at this point in the history
  • Loading branch information
Apidcloud committed Jan 13, 2025
1 parent 51b1f96 commit c640cde
Showing 1 changed file with 9 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,17 @@ private TimestampUtil() {}

public static int getMillisecondsFromTimestampString(String timestampString)
{
int milliseconds = 0;
int dotIndex = timestampString.indexOf('.');
if (dotIndex == -1) {
return 0;
}

if (dotIndex != -1) {
String fractionalPart = timestampString.substring(dotIndex + 1);
int fractionalLength = fractionalPart.length();
// Normalize the fractional part to at least 3 digits by padding with zeros. e.g., 7 -> 700; 70 -> 700
if (fractionalLength == 1) {
fractionalPart += "00";
}
else if (fractionalLength == 2) {
fractionalPart += "0";
}
milliseconds = Integer.parseInt(fractionalPart);
String fraction = timestampString.substring(dotIndex + 1);
int nonNormalized = Integer.parseInt(fraction);
if (nonNormalized == 0 || fraction.length() == 3) {
return nonNormalized;
}
return milliseconds;
// this will make sure it's always 3 digits. e.g., 7 -> 700; 71 -> 710; 7591 -> 759
return (int) Math.round(nonNormalized * Math.pow(10, -(Math.floor(Math.log10(nonNormalized)) - 2)));
}
}

0 comments on commit c640cde

Please sign in to comment.