Converting Google Maps distance measurements in decimal miles to int32 format

I am currently working on a project where I have an Asp.net text box that is being automatically populated by JavaScript using the Google Maps API. The text in the textbox can display varying distances ranging from 40.2 miles to 1,634 miles and so on.

My main goal is to extract the numerical value from the text box and convert it into an integer for storage in the database.

The challenge lies in ensuring that the extracted number is always in a rounded format, such as "40" or "1634", without any decimal points or extra characters.

I have attempted methods like Substring and Math.Round, but unfortunately, I keep encountering exceptions. Here is my latest try:

        string miles = txtEstDistance.Text;
        miles.Substring(0, miles.IndexOf('.') > 0 ? miles.IndexOf('.') : miles.Length);

        int oDistanceMiles = Convert.ToInt32(miles);

However, I am consistently getting the exception: "Input string was not in a correct format." specifically for this line of code:

int oDistanceMiles = Convert.ToInt32(miles);

I am feeling quite lost at this point. Using .Net 4.0 with C# programming language.

Answer №1

How about removing the " mi" first and then treating the remaining value as a floating-point number? Utilizing Math.Round, you can round it to the nearest whole number and then convert it to an integer.

Assuming that the NumberStyles.Float enum will automatically eliminate any leading or trailing white spaces. Additionally, you have the option of using string.Trim().

var distanceInMiles = txtEstDistance.Text;

distanceInMiles = distanceInMiles.Substring(0, distanceInMiles.IndexOf("mi"));

float temporaryDistance;
var result = float.TryParse(distanceInMiles, NumberStyles.Float, CultureInfo.InvariantCulture, out temporaryDistance);

if (result)
{
    var roundedDistance = Convert.ToInt32(Math.Round(temporaryDistance, 0));

    // alternatively

    roundedDistance = (int)Math.Round(temporaryDistance, 0);
}

Answer №2

When a dot is missing, the string appears as 40 mi, necessitating the use of a space.

miles.Substring(0, miles.IndexOf('.') > 0 ? miles.IndexOf('.') : miles.IndexOf(' '));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoiding conflicts between API calls in React's ComponentDidMount and ComponentDidUpdate phasesNote: The original text does not provide

When using the componentDidMount lifecycle method, I fetch data using a Redux action as shown below: componentDidMount() { let parameter = some code; this.props.getAction(parameter).then(r => { if(r.type.endsWith('SUCCESS')){ ...

Creating a Piechart in Kendo UI that is bound to hierarchal remote data

I am facing an issue with binding remote data to a pie chart while managing a grid with dropdown sorting options. The grid is working fine, but I am unable to display the hierarchical data on the pie chart as categories. <!DOCTYPE html> <html> ...

Leveraging log (or any other object from index.js) within nodejs modules

Recently, I came up with the idea of utilizing winston logging in my Node.js project. As I started configuring it, the setup began to expand. Initially, I had integrated it into my index.js file, but as the file grew larger, I decided to separate it into d ...

What is the best way to remove an object from a complex JavaScript array structure?

I'm having trouble removing an object from the array provided below. Whenever I try to delete its properties, they just turn into undefined. I have a recursive function that correctly identifies the object I want to remove. Specifically, I need to eli ...

Error: The src for the image of the double cheeseburger could not be properly parsed by the `next/image` component

Could you kindly take a moment to review this? import Image from "next/image"; import { useState, useEffect } from "react"; import "@/data/data.json"; interface propsData { dish: { id: numbe ...

Is it possible for Express in Node.js to handle multiple static folders at once?

Currently, I am working on a project that involves a user uploaded collection of styles, scripts, and images as well as my app's own collection of these resources. They are stored in separate directories on my server. I am wondering if there is a way ...

The Bootstrap drop-down feature refuses to open

I seem to be having trouble with a basic issue. I used the standard template from the bootstrap website, but for some reason, when I click on the dropdown menu in the navbar, it's not opening. Can someone help me figure out what's going wrong? & ...

Why is the updated index.html not loading with the root request?

I'm currently working on an Angular app and facing an issue with the index.html file not being updated when changes are made. I have noticed that even after modifying the index.html file, requests to localhost:8000 do not reflect the updates. This pro ...

Error in Javascript: Character class range is not in order

My regular expression (regex) seems to be incorrect: var domain = "google\.com\.br"; var reEmail = new RegExp("^([A-Za-z0-9_\-\.])+\@" + domain + "$"); I am trying to use this regex to validate an email address. Here is an exampl ...

Access the value from a JArray element that contains varying values

Currently, I am parsing a JSON file from an external partner that lacks consistency and is not expected to change any time soon. My objective is to extract the value of the field bathroom and save it as an integer. Below is a breakdown of the potential va ...

Navigating to the HTTPS webpage

Currently, I am in the process of adding an aspx page to my .net website where clients can input their credit card information. I want to restrict access to this page from only certain pages (let's say a.aspx and b.aspx), so if someone tries to access ...

Transferring input data between two HTML files in Electron with a secure login feature

Currently, I am in the process of developing an Electron app that facilitates communication between users through socket.io. The app includes a login screen where users can enter their registered email and password to access the main menu. For testing purp ...

The getElementById function can only select one option at a time and cannot select multiple options

I'm having an issue with a JavaScript function that is supposed to allow me to select multiple options, but it's only selecting the first one. Here is the JavaScript code: function index(){ var a="${staffindex}".replace("[",""); ...

JavaScript does not allow executing methods on imported arrays and maps

In my coding project, I created a map named queue in FILE 1. This map was fully built up with values and keys within FILE 1, and then exported to FILE 2 using module.exports.queue = (queue). Here is the code from FILE 1: let queue = new.Map() let key = &q ...

Showing and hiding nested Form Group validation in Angular 4 is a crucial feature that can improve

I have been exploring Angular 4 validation recently. Currently, I am working with a reactive form that contains two radio buttons and two form groups. The behavior I'm trying to achieve is when the user selects the first radio button, it removes valid ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Display a <div> every hour

I am attempting to display a <div> element once every hour. However, the code seems to be malfunctioning when I include the following: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div i ...

Combining Nested Objects in MongoDB

I have searched extensively for a solution but I am struggling to find a resolution to my issue. I have two MongoDB (Node.JS) collections: user & statistics. My goal is to merge the results using aggregate. Below are the structures of the collection ...

In a React Native application, images sourced from the database fail to display after the first initial view

After creating a React Native view called Work.js, I integrated portfolio information from a Supabase database. The data is then iterated through and displayed in a customized card component named WorkTile.js. Work.js import React, { useEffect, useState, ...

Interactive Zoomable Tree with d3.js

I am looking to customize the zoomable icicle plot in d3js by incorporating my own data. Unfortunately, I am unable to locate the "readme.json" file for data modification and cannot get the graph to display on my local machine. Where can I find this elus ...