格式化经纬度时末尾零丢失,如何保留6位小数带零?
How to Preserve 6 Decimal Places (Including Trailing Zeros) for Latitude/Longitude Formatting
The problem here lies in your DecimalFormat pattern: ##.###### uses #, which acts as an optional digit placeholder. This means trailing zeros in the decimal section get dropped because they aren’t considered "required" to represent the number.
To force exactly 6 decimal places (and keep any trailing zeros), swap out the # placeholders in the decimal portion with 0. Here’s the fixed formatting function:
fun formattLatLong(latOrLong: Double): String { val df = DecimalFormat("##.000000") return df.format(latOrLong) }
Quick breakdown of the updated pattern:
##: Handles the integer part of the coordinate. It displays only the digits needed (no unnecessary leading zeros), which works perfectly since latitude ranges from -90 to 90 and longitude from -180 to 180..000000: Guarantees exactly 6 digits after the decimal point. If the original value has fewer than 6 decimal digits, it pads with zeros; if it has more, it rounds to 6 digits (a standard behavior for coordinate formatting).
Once you update the function, your output will look like this:
Location : 23.044380,72.529783
lat : 23.044380 lng : 72.529783
This meets your requirement of retaining 6 decimal places with trailing zeros intact.
内容的提问来源于stack exchange,提问作者Nensi Kardani
相关产品推荐
相关产品推荐

