Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I formatted numbers when input happinig in textbox.But PHP doest get it in as formatted number.

For example When user inpuputted money as
34.000.000,23
, then PHP uotputting this
34


How can I solve this issue ?

Thanks
Posted

1 solution

Hi, you may consider using the following code.
As PHP derives heavily from C, it has a number of functions and behaviours that are similar/identical.

One function of use is sscanf, which allows you to scan a string for particular types of data. You can grab strings, numbers and characters for instance. In my understanding, neither C nor PHP's sscanf function were designed to use decimal separators other than a period. Also,they're not designed for use with thousands-separators either.

With this in mind, we can go about transforming the string into something that sscanf will handle. We can then grab it as a floating-point number and perform mathematical operations on it. We can then finally convert this number back into a string representation, even being able to specify which character is used for both types of separator.

PHP
<?php
    $inputStr = '34.000.000,23';
    echo $inputStr . '<br>';

    // turn the string into a format sscanf will work with.
    // this involves removing the thousands-separators  and making the decimal separators  a period (.)
    $numberStr = str_replace('.', '', $inputStr);
    $numberStr = str_replace(',', '.', $numberStr);

    //now get the string of a number into an actual number we can do calculations with.
    sscanf($numberStr, '%f', $number);

    //double the number
    $number *= 2;

    // make a string of this value, with 2 places after the decimal point, using (,) as the decimal seperator,
    // and (.) as the thousands separators
    $outputStr = number_format($number, 2, ',', '.');


    echo $outputStr . "<br>";
?>


Output
34.000.000,23
68.000.000,46
 
Share this answer
 
Comments
Tahsin Çetin 28-Feb-15 14:50pm    
Ok Thanks.sscanf has done my issue

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900