如何获取float类型当前时间?解决图表时间精度丢失问题
Great question—this is a super common gotcha when dealing with timestamps and float precision! Let’s break down what’s happening and how to fix it.
The Core Problem
First, why are you losing precision when parsing those timestamp strings to float? Because float only has 6-7 significant digits of precision. Your timestamps (from calendar.getTimeInMillis()) are 13-digit long values, which is way more than float can handle accurately. When you convert a 13-digit long to float, the last few digits get truncated or rounded—there’s no way around this with raw absolute timestamps and float.
You can’t "directly get a float type of time" that retains full precision of the original long timestamp, since float doesn’t have enough bits to store that much data. But there are easy workarounds!
The Best Fix: Use Relative Timestamps
Instead of using absolute timestamps, calculate time relative to your first data point. This shrinks the numerical value enough that float can represent it accurately. Here’s how to adjust your code:
// First, get the base timestamp (the first entry in your list) if (!arrayListTime.isEmpty()) { long baseTimestamp = Long.parseLong(arrayListTime.get(0)); for(int i = 0; i < arrayListTime.size(); i++) { // Calculate time relative to the first entry long currentTimestamp = Long.parseLong(arrayListTime.get(i)); float relativeTime = (float) (currentTimestamp - baseTimestamp); // Parse pulse as before float pulseValue = Float.parseFloat(arrayListPuls.get(i)); entries.add(new Entry(relativeTime, pulseValue)); } }
Why This Works
The relative time values will be much smaller (e.g., if your data spans minutes, the relative time will be in the thousands or tens of thousands of milliseconds—way under 7 digits). Float can represent these values perfectly without precision loss.
When you’re labeling your chart’s x-axis, you can:
- Show labels like "0s", "30s", "1m" (relative to start time)
- Or store the base timestamp separately, then convert the relative values back to absolute timestamps when creating axis labels
Alternative: Scale the Timestamp Unit
If relative time doesn’t fit your use case, you can scale the timestamp to a larger unit (like seconds or minutes) to reduce the number of digits:
for(int i = 0; i < arrayListTime.size(); i++) { long timestamp = Long.parseLong(arrayListTime.get(i)); // Convert milliseconds to seconds (divide by 1000.0f to keep it a float) float timeInSeconds = timestamp / 1000.0f; float pulseValue = Float.parseFloat(arrayListPuls.get(i)); entries.add(new Entry(timeInSeconds, pulseValue)); }
Note: This still might lose some precision if your data spans years (since a 10-digit second timestamp is still pushing float’s limits), but it’s better than using raw milliseconds. Relative time is still the more reliable option.
内容的提问来源于stack exchange,提问作者Apri

