简体   繁体   English

从字符串转换为数字的问题

[英]Problem with converting from string to number

I have a variable $totalprice with number 1,072.00. 我有一个变量$ totalprice与数字1,072.00。

If I use int($totalprice) or number_format($totalprice), it outputs 1.00. 如果我使用int($ totalprice)或number_format($ totalprice),则输出1.00。

How can I solve this problem? 我怎么解决这个问题? I want 1072.00 我要1072.00

$totalprice = (float)str_replace(',', '', $totalprice)

That will get you a normal float representation of the number. 这将使您可以正常表示该数字。 You can then apply the number_format function to that to get the desired output. 然后,您可以将number_format函数应用于该函数以获取所需的输出。

Perhaps you should rethink your handling of numbers. 也许您应该重新考虑对数字的处理。 How in the first place the number gets the format 1,072.00 ? 数字如何首先获得1,072.00的格式? You shouldn't do any formatting to it until outputting to the browser, so the number should always be in the 1072.00 format. 在输出到浏览器之前,请勿对其进行任何格式化,因此数字应始终为1072.00格式。

Problem you are having is about locales. 您遇到的问题与语言环境有关。 To avoid issue about money formatting i would suggesT you to use 为避免有关货币格式的问题,我建议您使用

string money_format ( string $format , float $number )

By using this function you can format the number according to desired format. 通过使用此功能,您可以根据所需格式设置数字格式。 you can read more about this function and what formatting type to use here: money_format 您可以在此处阅读有关此功能的更多信息以及要使用的格式类型: money_format

It is not a bug ,because your number is parsed from left till first invalid character (the , ) 这不是错误,因为您的号码是从左到第一个无效字符( )解析的

so 1,072.00 is really 1 ,072.00 , and just the bold section is parsed when you are trying to convert the string to number. 因此1,072.00真的是1,072.00,只是当你试图将字符串转换为数字大胆的部分进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM