The Number.toLocaleString function does not work properly in the pt-BR locale when tested in

A function named toCurrency has been created for converting strings or numbers to locale-specific formats:

function toCurrency(
    value: string | number,
    locale: string = "en-US",
    currency: string = "USD",
    options?: Intl.NumberFormatOptions
) {
    return Number(value).toLocaleString(locale, {
        maximumFractionDigits: 2,
        style: "currency",
        currency: currency,
        ...options,
    });
}

There is also a test suite designed to validate this function:

describe("toCurrency", () => {
    test("toCurrency defined", async () => {
        expect(toCurrency).toBeDefined();
    });

    test("toCurrency conversion with pt-BR locale and BRL currency", () => {
        const result = toCurrency(1, "pt-BR", "BRL");
        expect(result).toEqual("R$ 1,00");
    });
    
    test("toCurrency conversion with en-US locale and USD currency", () => {
        const result = toCurrency(1, "en-US", "USD");
        expect(result).toEqual("$1.00");
    });
});

However, the tests are failing specifically when using the pt-BR locale:

https://i.sstatic.net/UDOBa7NE.png

Answer №1

It's possible that the Node.js version you're using has a different CLDR data version than expected by your test, resulting in varied outcomes for toLocaleString.

Alternatively, if your test hasn't been tailored to the CLDR data, it might anticipate a standard 0x20 space between R$ and the number. However, the formatted character could actually be a non-breaking space like \xA0:

> function toCurrency(
...     value,
...     locale = "pt-BR",
...     currency = "BRL"
... ) {
...     return Number(value).toLocaleString(locale, {
...         maximumFractionDigits: 2,
...         style: "currency",
...         currency,
...     });
... }
> toCurrency(1)
'R$ 1,00'
> [...toCurrency(1)].map(c => c.codePointAt(0))
[
  82, 36, 160, 49,
  44, 48,  48
]

Notice how the third codepoint is 160, which represents 0xA0.

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

To modify a list

I'm facing a challenge where I need to restructure an array, but I'm not sure where to begin. Here is the original array: var products = [ "rose-S", "rose-M", "rose-L", "rose-XL", "rose- ...

Best practices for linking Websocket events to refresh my React Component

Although my main focus is C++ backend development, I've been dabbling in learning React on the side. I have written a simple file to utilize websockets. import React, { useState } from "react"; var serverMessage = ""; var webSocke ...

How to monitor and respond to HTML modifications in a child component from a parent component in Angular framework

In the setup I have, there is a main component known as @Component({ selector: 'parent-comp' template: '<child-comp [inputData]="responseData"></child-comp> }) export class ChildComponent { public responseData: any; ...

Struggling to execute a basic Typescript file

I recently embarked on a journey to learn Typescript by enrolling in this specific course. The process of setting up everything seemed simple enough. I created a new directory, executed the command npm init, and followed it up with npm install --save-dev t ...

Issue with VueJS component prop displaying only the last JSON entry when it is reused

My aim is to reuse a vue component with a prop that takes data from a json object. However, the issue I'm facing is that all instances of the component are displaying the same data instead of data based on the index of the json object. This is how my ...

Variations in how words are organized within a sentence

Can you help me devise an algorithm to identify all possible combinations of word groupings in a sentence without changing the order of the words? For example, for the sentence "the test case phrase," the various combinations would include: ['the te ...

Removing the hash symbol in Angular: A step-by-step guide

My experience with AngularJS is new, and I am currently working on removing the # from the URLs without utilizing NODE or Express. The project is being hosted locally on MAMP, with index.html acting as the main entry point. Within the structure, there are ...

JavaScript onclick event triggers only the second audio to play

Does anyone have experience with adding sound effects to a website? I'm attempting to have a positive sound play when the correct image is clicked and a negative sound play when the wrong image is clicked. However, regardless of which image I click on ...

Tips for integrating global functionalities such as Create, Methods, and Mounted from a plugin into Vue

In certain scenarios, I prefer not to utilize mixins in my Plugin. Instead, I am working on incorporating custom methods like `created()`, `mounted()`, and `methods{}` so that I can access its property when the component loads and execute my own custom me ...

Encountering an issue while retrieving data from my personal server: "Error message states 'Unexpected end of JSON input'."

As a beginner in Backend development, I decided to experiment with API calls and Client-Server interactions. const express = require("express"); const cors = require("cors"); const fetch = require("node-fetch"); const app = e ...

d3js graphics, Opt for utilizing json strings over json file

My first experience with d3js was while utilizing the Line Chart Sample provided by this link. Despite successfully loading the data as seen in Firebug, the chart itself failed to display the data. I am unable to identify the issue and would greatly apprec ...

Struggling with integrating an EJS form to work with a MONGODB database

I'm struggling to wrap my head around how to connect the front end in ejs and submit a form that sends information to the back end. At the moment, I have a file called server.js that renders all my ejs pages and connects to the database. Here is the ...

Expo - The package name 'com.xxx.native.xxx' specified in AndroidManifest.xml is invalid for use in Java, as 'native' is a reserved Java keyword

For as long as I can remember, I've been using the pattern 'com.mycompanyname.native.appname' to name the bundle Ids for my apps. This approach has served me well over the years and I've created numerous apps with the keyword "native" i ...

typescript error in navigating with parameters

Having trouble adding a param with TypeScript and encountering the following error: Error: Argument of type '["Profile", { screen: Screen; }]' is not assignable to parameter of type '[screen: "Explore"] | [screen: "E ...

Alert: Prop type validation error: The `component` prop provided to `ForwardRef(Link)` is invalid

We are facing an issue with our NextJS app where it works fine in production, and locally it renders correctly. However, we are encountering some unsightly warnings that we are trying to suppress. client.js:1 Warning: Failed prop type: Invalid prop `compon ...

Unexpected behavior in AJAX call

I'm currently working on implementing an AJAX call to display a partial view once a radio button is selected. Despite following the recommendations found on Stack Overflow comments, I am encountering difficulties. Upon selecting the radio button, ther ...

Could you explain the concept of implodeQuery to me?

While browsing through the source page of Facebook, I came across a function that is commonly used. The specific line of code was: input_len=URI.implodeQuery(this.data).length I am having trouble understanding what this line of code means and what exactl ...

Merging Related Objects into a Single Object Array (JavaScript)

I have extracted user and permission data from my database and now I want to merge the access object with each user object so that I can easily access all the necessary information when displaying user permissions on a page in my application. Luckily, the ...

Having trouble with Append() function not functioning properly within the if statement nested inside a .each loop in jQuery

Looking to add text after the 4th element in a ul li? I tried using the append function, but it's appending before every li element. Here's the HTML: <ul class="gallery"> <li><a href="#">Some Text</a> ...

Utilizing jQuery to compute dynamic fields depending on selection in a dropdown menu

Creating a Ruby app for tracking bets, I have designed a small form that captures various details including date and match. However, the most crucial components of this form are the "stake" and "odd" text fields. To enhance user experience, I have incorpor ...