ChungaMagnet
ChungaMagnet

Reputation: 1

Separate a price/number by a comma in React

I am cloning amazon for my portfolio. have a price in React like this: price={37.84}. I want the price to display like this: price={37,84}. The price that appears is 84. Is there a way to display the price as 37,84?

Code:

<div className="home__row">
          <Product
            id="12321341"
            title="Learning React: Modern Patterns for Developing React Apps 2nd Edition"
            price={37,84}
            rating={5}
            image="https://images-na.ssl-images-amazon.com/images/I/51Kwaw5nInL._SX379_BO1,204,203,200_.jpg"
          />

Product Component:

import React from "react";
import "./Product.css";
import { useStateValue } from "./StateProvider";

function Product({ id, title, image, price, rating }) {
  const [{ basket }, dispatch] = useStateValue();

  const addToBasket = () => {
    // dispatch the item into the data layer
    dispatch({
      type: "ADD_TO_BASKET",
      item: {
        id: id,
        title: title,
        image: image,
        price: price,
        rating: rating,
      },
    });
  };

  return (
    <div className="product">
      <div className="product__info">
        <p>{title}</p>
        <p className="product__price">
          <small>€</small>
          <strong>{price}</strong>
        </p>
        <div className="product__rating">
          {Array(rating)
            .fill()
            .map((_, i) => (
              <p>🌟</p>
            ))}
        </div>
      </div>

      <img src={image} alt="" />

      <button onClick={addToBasket}>Add to Basket</button>
    </div>
  );
}

export default Product;

Upvotes: -2

Views: 3774

Answers (3)

jonrsharpe
jonrsharpe

Reputation: 122135

Using a comma as the decimal separator is not supported in JavaScript code, you can't have that in a number literal. However, you can use the locale functionality to format numbers as strings that way, for example using a number's toLocaleString method:

> 37.84.toLocaleString("en-de");  // based on your profile
"37,84"

If you do try to use a comma, it's the comma operator and you just end up with the right-most value:

> 37,84
84

Upvotes: 5

utopy
utopy

Reputation: 1

There are two ways to solve this problem, and the method is pretty much the same: convert the float to string and replace the dot.

String(price).split(".").join(",")
String(price).replace(".", ",")

this should work :)

Upvotes: 0

Johannes Klau&#223;
Johannes Klau&#223;

Reputation: 11040

Use price={"37,84"} to display it as a string.

Or if you have a variable containing a price use this:

price={price.replace('.', ',')}

Upvotes: 1

Related Questions