How did I end up facing two distinct decimal separators side by side like this?

As I find myself in France where the decimal separator is a comma, I have created this component that showcases a discrepancy in displaying numbers:

  • Both commune.population and commune.surface are decimal numbers (with the type number)
  • However, they unexpectedly show different decimal separators: a point for surface and a comma for density.

Commune with 176016 inhabitants and an area of 80.03 km² (density: 2,199)
within the Saint-Etienne Métropole intermunicipal authority

Why is this happening?

<div class="row">
  <div class="presentation_cadre" id="presentation_cadre">
    <ng-template [ngIf]="isCommuneSelected()" [ngIfElse]="pasDeCommuneSelectionnee">
      <div>
        <h4>{{ commune.nomCommune }} ({{ commune.nomDepartement }} ({{ commune.codeDepartement }}))</h4>

        <small>
          <div>Commune with {{ commune.population }} inhabitants and {{ commune.surface / 100.0 }} km² (density: {{ this.getDensitePopulation() | number:'1.0-0' }})</div>
          <div>within the {{ commune.nomEPCI }} intermunicipal authority</div>
        </small>
      </div>
    </ng-template>

    <ng-template #pasDeCommuneSelectionnee>
      Information about a commune will be displayed here
    </ng-template>
  </div>
</div>
public getDensitePopulation() : number {
  if (this.commune == null || this.commune.surface == 0) {
    return 0
  }

  let surfaceKm2 = this.commune.surface / 100.00; // The surface is in hectares
  return this.commune.population / surfaceKm2
}

Answer №1

When it comes to density calculation, the DecimalPipe is utilized, performing the following function as outlined in the documentation:

The DecimalPipe formats a value based on digit options and specific locale rules. The locale determines group sizing and separator, decimal point character, along with other locale-specific configurations.

Given that the current locale is set to FR (France), the formatting involves using a comma. If you wish to format the number according to the specific locale manually, you can easily achieve this by utilizing the toLocaleString method:

// I am passing "FR" here to demonstrate the output for the French locale.
// This parameter is optional; if omitted, it defaults to the user's locale
console.log((80.03).toLocaleString("FR"));

Applying this concept to your scenario, the code would look something like this:

{{ (commune.surface / 100.0).toLocaleString() }}

For more information, refer to: MDN Number.prototype.toLocaleString

However, for consistency purposes, it's advisable to utilize another DecimalPipe when dealing with area calculations.

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

Converting Boolean Values to Strings in Ionic/Angular NGX Datatable

Currently, I am working on a project to develop an Ionic/Angular application. For this application, I am utilizing NGX datatable which is functioning well. However, I have a specific requirement - I need to display boolean values in German instead of Engli ...

TypeScript: Defining a custom object type using an array of objects

Is there a way to dynamically generate an object based on the name values in an array of objects? interface TypeA { name: string; value: number; } interface TypeB { [key: string]: { value: any }; } // How can we create an OutputType without hard ...

Confirming that the NGRX Dictionary value is set

After upgrading from Angular 7.1.4 to 8.2.0 and Typescript from 3.1.6 to 3.5.3, I encountered an issue with identification of array items. Prior to the upgrade, TypeScript correctly recognized that the array item was not undefined. However, post-upgrade, ...

Displaying icons representing different countries using Angular framework

Seeking assistance with Angular - I obtained a collection of country icons (svg format) from flat icon and intend to display them based on the respective countries in my project. With 870 icons, what would be the simplest approach to accomplish this with ...

Utilizing Angular 2's ViewChild within the <router-outlet> Tag

I've been working on a project using Angular 2. Within the MainComponent, I'm utilizing @ViewChild to reference child components. The MainComponent also contains a <router-outlet> where various components are loaded. My query is, how can I ...

What could be the reason for Typescript attempting to interpret files in the `./build` directory as input files?

After struggling for an hour on this issue, I am stuck. The variables outDir and rootDir are set. However, the problem arises when only src is included in include, TypeScript shows the configuration via showConfig, yet it's attempting to compile 4 fi ...

Exploring the Concept of Angular4 Component Nesting and Input Issues

I've taken on the challenge of completing an exercise from the book "Angular From Theory To Practice - Asim Hussain". The exercise involves refactoring an app using Angular CLI instead of having all components in the same file. You can find a sample f ...

Checking for non-falsy variables that include 0 in JavaScript

What is a more graceful method for checking if a variable is truthy but also passes when it's equal to 0? The current verification if(var !== undefined && var !== null) is lengthy and doesn't account for all scenarios such as undefined or ...

Lazy-loaded modules in Angular that contain services provided within the module

Currently, I am facing a challenge with lazy-loaded modules and services that are provided in these modules. My folder structure looks like this: app -> featureModule1 (lazy loaded) -> featureModule2 (lazy loaded) -->services --->servi ...

What strategies can I employ to prevent redundancy when all my .vue files are identical?

Although I am new to Vue, there are many aspects that I find appealing. However, one thing I dislike is combining templates, scripts, and styles in the same file. Instead, I prefer separating these concerns by using: <template src="./template.html"> ...

Messages are not being emitted from the socket

I've been encountering an issue with message transmission from client to server while using React and ExpressJS. When I trigger the sendMessage function on the client side, my intention is to send a message to the server. However, for some reason, the ...

Troubleshooting Issues with Uploading Images to Firebase Storage Using ReactJS, JavaScript, and Firebase

Despite watching countless tutorials and conducting thorough research, I continue to encounter errors in my code. One recurring error can be seen in the image below: https://i.sstatic.net/AmG5D.png In one file, I include the line import firebase from &apo ...

Achieving (keyup.enter) event on an option within a datalist in Angular 6

How can I trigger the (keyup.enter) event on an option within a datalist in Angular 6? This is my HTML Code: <input list="filteredArray" (keyup)="filterEmployee(empForm.controls['empname'].value)" type="text" formControlName="empname" /> ...

Tips for showcasing images and videos in a full-screen mode resembling the TIKTOK APP through the use of Angular, Ionic 4, and Capacitor

Currently, I am diving into the world of Angular Ionic 4 with Capacitor. My goal is to create a feature that allows images and videos to be displayed in full screen, similar to how it works in the TikTok app. If anyone has experience with this functional ...

Tips for utilizing the onClick handler when mapping through items in React

Currently, I am a student learning about react. During the course of working on a project, I encountered a problem that left me with a question. {pages.map((page, idx) => ( <li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}> < ...

Testing Angular Components with setInterval FunctionTrying out unit tests in Angular

I'm struggling to figure out how to write unit tests for setInterval in my .component.ts file. Here is the function I have: startTimer() { this.showResend = false; this.otpError = false; this.time = 60; this.interval = setInterval(() => { this.ti ...

Attempt retrieving a value in TypeScript using TryGet without non-standard type

Is there a way to implement a TryGet pattern similar to C#'s out in TypeScript? For instance: if(TryGetFoo(out Foo foo) { Debug.Log("Got the foo, and here is it's bar: " + foo.bar); } else { Debug.Log("Can't get the foo!"); } The i ...

Creating a generic union type component in Typescript/Angular 10

My interfaces are as follows: export interface Channel { id: number; name: string; } export interface TvChannel extends Channel { subscribed: boolean; } export interface RadioChannel extends Channel { // marker interface to distinguish radio chan ...

The returned type of intersected functions in Typescript does not match the inferred type

While attempting to extract the return type of an intersected request, I encountered a discrepancy between the return type and the inferred type. Check out the shortened URL for more details: https://tsplay.dev/mAxZZN export {} type Foo = (() => Promis ...

What are the steps to resolve the issue of assigning void type to type ((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) | undefined in a react application?

I'm trying to update the state isOpen to true or false when clicking on a div element, but I keep getting an error with the following code: function Parent() { const [isOpen, setIsOpen] = React.useState(false); return ( <Wrapper> ...