javascript - 如果是整数,则追加 ,00
问题描述
我需要附加一个小数,但带有一个昏迷,所以如果是300它应该更改为300,00我有下面的代码并且它可以工作,但如果数字已经是一个小数,它会将它更改为NAN。我需要代码不要修改已经是小数的数字
var formatter = new Intl.NumberFormat('es-ES', {
style: 'currency',
currency: 'USD',
});
$('.total-amount').each(function() {
var x = $(this).text().replace(/[^\d,]/g, "");
$(this).text(formatter.format(x));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total-in-basket">
<div class="total-description">
total is:
</div>
<p> with decimal example: </p>
<div class="total-amount">
$ 300,00
</div>
<p> without decimal example: </p>
<div class="total-amount">
$ 300
</div>
</div>
解决方案
您可以简单地再添加一个来替换 ( , )replace
之后的尾随文本
例子:
var formatter = new Intl.NumberFormat('es-ES', {
style: 'currency',
currency: 'USD',
});
$('.total-amount').each(function() {
var x = $(this).text().replace(/[^\d,]/g,"").replace(/,.*$/g,""); /*<- add this*/
$(this).text(formatter.format(x));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total-in-basket">
<div class="total-description">
total is:
</div>
<p> with decimal example: </p>
<div class="total-amount">
$ 300,00
</div>
<p> without decimal example: </p>
<div class="total-amount">
$ 300
</div>
</div>
推荐阅读
- c# - 从 .netframework 4.6 迁移到 .Net core 3.1
- reactjs - React Apollo useQuery - how it works
- node.js - Node.Js 500+ 项搜索
- vue.js - Vue & Vuex 中如何正确绑定表单 - v-model、:value & :value.sync 的区别
- laravel - Laravel - 我尝试显示警报“如果由于在另一个表中分配而无法删除数据”而不是显示错误
- java - 如何使用匕首在相互依赖的类中提供依赖关系
- docker - 通过 docker 在单个 Tomcat 实例上运行不同的 webapp 镜像
- javascript - 使用 PHP 在电子邮件中发送表单数据而不刷新页面
- python - 使用 SymPy 解决包含 Abs() 操作的复杂系统
- rocket.chat - 在火箭聊天中添加 Facebook 和 gmail 登录功能