在React中用逗号分隔价格/数字

问题描述

我正在为我的投资组合克隆亚马逊。在React中有这样一个价格:price={37.84}。我希望价格显示为:price={37,84}显示的价格为84。是否可以将价格显示37,84

代码

<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"
          />

产品组件:

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;

解决方法

使用逗号作为JavaScript代码中的十进制分隔符,您不能在数字文字中使用逗号。但是,您可以使用语言环境功能以这种方式将数字格式化为字符串,例如,使用数字的toLocaleString method

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

如果您确实尝试使用逗号,则为comma operator,最后得到最右边的值:

> 37,84
84
,

使用price={"37,84"}将其显示为字符串。

或者,如果您有一个包含价格的变量,请使用以下代码:

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

有两种方法可以解决此问题,方法几乎相同:将浮点数转换为字符串并替换点。

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

这应该有效:)