0

I need to modify the request parameters in the GET URL "http://localhost:8081/qeats/v1/restaurants?latitude=87.97864&longitude=20.82345" while sending it to spring boot controller such that the latitude and longitude values are only precise up to the single decimal place. e.g "http://localhost:8081/qeats/v1/restaurants?latitude=87.9&longitude=20.8"

@GetMapping(RESTAURANTS_API)
  public ResponseEntity<GetRestaurantsResponse> getRestaurants(
  @RequestParam Double latitude,
  @RequestParam Double longitude, GetRestaurantsRequest getRestaurantsRequest) {
        
  
log.info("getRestaurants called with {}", getRestaurantsRequest);

GetRestaurantsResponse getRestaurantsResponse;

if (getRestaurantsRequest.getLatitude() != null && getRestaurantsRequest.getLongitude() != null
    && getRestaurantsRequest.getLatitude() >= -90 
      && getRestaurantsRequest.getLatitude() <= 90
        && getRestaurantsRequest.getLongitude() >= -180 
          && getRestaurantsRequest.getLongitude() <= 180) {

  getRestaurantsResponse = restaurantService.findAllRestaurantsCloseBy(
      getRestaurantsRequest, LocalTime.now());
  log.info("getRestaurants returned {}", getRestaurantsResponse);
  return ResponseEntity.ok().body(getRestaurantsResponse);
} else {
  return ResponseEntity.badRequest().body(null);
}
Meet Gujrathi
  • 65
  • 1
  • 6
  • See : https://www.programiz.com/java-programming/examples/round-number-decimal – Sahil Gupta Aug 26 '20 at 18:01
  • According to your requirement, you can convert latitude and longitude value to desired value from client-side (from frontEnd) from backEnd editing Requestparam is complicated. – Shubham Aug 26 '20 at 18:12

1 Answers1

0

you can add a custom Formatter or Converter, for example:

  1. implement the custom Formatter:
    public class MyDoubleFormatter implements Formatter<Double> {

        private final DecimalFormat decimalFormat = new DecimalFormat("#.#");

        @Override
        public Double parse(String text, Locale locale) {
            return Double.parseDouble(decimalFormat.format(Double.parseDouble(text)));
        }

        @Override
        public String print(Double value, Locale locale) {
            return value.toString();
        }
    }
  1. register the custom Formatter:
    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {

        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addFormatter(new MyDoubleFormatter());
        }
    }
tsarenkotxt
  • 3,231
  • 4
  • 22
  • 38