John Davidson

PHP string has thousand Separators Multiplication

0 comments
Message:


I have two strings. the one has a thousand separator as a comma, the other one has a decimal point as a dot.


below is my example code for explanation.


$number1 = "250,000";
$number2 = "1.000";

what I want to do is to multiply those two strings. I somewhat found that PHP thinks the comma as a floating point!


echo number_format($number1 , 3, ".", ",");

//result : 250.000 value type is still a string

I have already used the floatval() method but maybe i havn't used it in a proper way.


please can anyone help me with this problem? I want to multiply those two...



My Answer:
"1,000";
$number2 = "2.5";

// Remove thousand separator and convert to float
$number1 = (float) str_replace(",", "", $number1);

// Multiply the two numbers
$result = $number1 * $number2;

echo $result; // Output: 2500

Rate this post

5 of 5 based on 7095 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us