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

-2 currency-formatting reactjs

我正在为我的投资组合克隆亚马逊。React 中有这样的价格:price={37.84}。我希望价格显示如下:price={37,84}。显示的价格是 84。有没有办法将价格显示为37,84

\n

代码:

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

产品组成:

\n
import React from "react";\nimport "./Product.css";\nimport { useStateValue } from "./StateProvider";\n\nfunction Product({ id, title, image, price, rating }) {\n  const [{ basket }, dispatch] = useStateValue();\n\n  const addToBasket = () => {\n    // dispatch the item into the data layer\n    dispatch({\n      type: "ADD_TO_BASKET",\n      item: {\n        id: id,\n        title: title,\n        image: image,\n        price: price,\n        rating: rating,\n      },\n    });\n  };\n\n  return (\n    <div className="product">\n      <div className="product__info">\n        <p>{title}</p>\n        <p className="product__price">\n          <small>\xe2\x82\xac</small>\n          <strong>{price}</strong>\n        </p>\n        <div className="product__rating">\n          {Array(rating)\n            .fill()\n            .map((_, i) => (\n              <p></p>\n            ))}\n        </div>\n      </div>\n\n      <img src={image} alt="" />\n\n      <button onClick={addToBasket}>Add to Basket</button>\n    </div>\n  );\n}\n\nexport default Product;\n
Run Code Online (Sandbox Code Playgroud)\n

jon*_*rpe 5

JavaScript 代码不支持使用逗号作为小数点分隔符,因此不能在数字文字中使用逗号。但是,您可以使用区域设置功能将数字格式化为字符串,例如使用数字的toLocaleString方法

> 37.84.toLocaleString("en-de");  // based on your profile
"37,84"
Run Code Online (Sandbox Code Playgroud)

如果您确实尝试使用逗号,那么它就是逗号运算符,您最终会得到最右边的值:

> 37,84
84
Run Code Online (Sandbox Code Playgroud)