2014-10-03 2 views
0

, когда я отправлю 1,000,000, отображается как 1, но если я отправлю 1000000, отображается как 1,000,000. Я хочу, чтобы выход был 1,000,000, независимо от того, как он отправлен. Пожалуйста, помогите!Как отключить преобразование десятичной точки в php

Вот PHP код:

if(!function_exists('get_property_price')){ 
    function get_property_price(){ 
     global $post; 
     $price_digits = doubleval(get_post_meta($post->ID, 'REAL_HOMES_property_price', true)); 
     if($price_digits){ 
      $currency = get_theme_currency(); 
      $price_post_fix = get_post_meta($post->ID, 'REAL_HOMES_property_price_postfix', true); 
      $decimals = intval(get_option('theme_decimals')); 
      $decimal_point = get_option('theme_dec_point'); 
      $thousands_separator = get_option('theme_thousands_sep'); 
      $currency_position = get_option('theme_currency_position'); 
      $formatted_price = number_format($price_digits,$decimals, $decimal_point, $thousands_separator); 
      if($currency_position == 'after'){ 
       return $formatted_price . $currency. ' ' . $price_post_fix; 
      }else{ 
       return $currency . $formatted_price . ' ' . $price_post_fix; 
      } 
     }else{ 
      return __('NA','framework'); 
     } 
    } 
} 

if(!function_exists('property_price')){ 
    function property_price(){ 
     echo get_property_price(); 
    } 
} 

if(!function_exists('get_custom_price')){ 
    function get_custom_price($amount){ 
     $amount = doubleval($amount); 
     if($amount){ 
      $currency = get_theme_currency(); 
      $decimals = intval(get_option('theme_decimals')); 
      $decimal_point = get_option('theme_dec_point'); 
      $thousands_separator = get_option('theme_thousands_sep'); 
      $currency_position = get_option('theme_currency_position'); 
      $formatted_price = number_format($amount,$decimals, $decimal_point, $thousands_separator); 
      if($currency_position == 'after'){ 
       return $formatted_price . $currency; 
      }else{ 
       return $currency . $formatted_price; 
      } 
     }else{ 
      return __('NA','framework');}}} 
+0

Вы сомневаетесь, что это неправильно. PHP не преобразует эти значения в десятичные значения разделенных значений, ваша инфраструктура делает. В вашей теме найдите опции 'theme_thousands_sep' и' theme_dec_point'. – GuyT

+0

Возможный дубликат [Разбор номера, но сохранить отрицательный] (http: // stackoverflow.com/questions/19964723/parse-a-number-but-keep-negatives) – Tigger

+0

GuyT Я попытался отключить их из функции.php bt никаких изменений –

ответ

0

Проблема проста в понимании.

Функция doubleval выполняет (преобразует) значения в числа с плавающей запятой.

Например, строка «1000.55» будет преобразована в плавающую точку, представляющую число, приближенное к 1000.55. Но строка «1,000.55» будет преобразована в 1, потому что 1000.55 не является допустимым представлением с плавающей запятой. Компараты не существуют в представлениях с плавающей запятой PHP, поэтому строка усекается перед преобразованием в плавающее poing.

Я считаю, функцию, которую я осуществил может решить вашу проблему, как это:

function formattedprice2float($formatted_price) { 
    $decimal_point  = get_option('theme_dec_point'); 
    $thousands_separator = get_option('theme_thousands_sep'); 

    $price_string = str_replace(array($decimal_point, $thousands_separator), 
           array('.', ''), 
           $formatted_price); 
    return is_numeric($price_string) ? (float)$price_string : null; 
} 

if(!function_exists('get_property_price')){ 
    function get_property_price(){ 
     global $post; 
     $price_digits = formattedprice2float(get_post_meta($post->ID, 'REAL_HOMES_property_price', true)); 
     if($price_digits){ 
      $currency = get_theme_currency(); 
      $price_post_fix = get_post_meta($post->ID, 'REAL_HOMES_property_price_postfix', true); 
      $decimals = intval(get_option('theme_decimals')); 
      $decimal_point = get_option('theme_dec_point'); 
      $thousands_separator = get_option('theme_thousands_sep'); 
      $currency_position = get_option('theme_currency_position'); 
      $formatted_price = number_format($price_digits,$decimals, $decimal_point, $thousands_separator); 

      if($currency_position == 'after'){ 
       return $formatted_price . $currency. ' ' . $price_post_fix; 
      }else{ 
       return $currency . $formatted_price . ' ' . $price_post_fix; 
      } 
     }else{ 
      return __('NA','framework'); 
     } 
    } 
} 

Я предполагаю, что get_post_meta($post->ID, 'REAL_HOMES_property_price', true) возвращается что-то вроде «1000000». Я не могу проверить это, потому что у меня нет всех необходимых файлов, но попробуйте.

+0

Привет, Педро. Спасибо, что он работал как волшебство. Я очень ценю за ваше время и помощь. Продолжайте с тем же дух! :) –

0

Вы можете удалить символ, прежде чем обрабатывать цены с str_replace()

Ваш будет выглядеть, как это потом, если вы хотите удалить запятую:

$price_digits = doubleval(str_replace(',', '', get_post_meta($post->ID, 'REAL_HOMES_property_price', true)); 
+0

Виктор благодарит за помощь, но str_replace() приводит к ошибке на веб-сайте. Есть ли другой способ –

+0

В моем коде была опечатка. Я изменил это сейчас – Victor

1

Посмотрите на numfmt_parse. Много подробнее здесь: http://php.net/manual/en/numberformatter.parse.php

Вот пример из PHP документации:

<?php 
$fmt = numfmt_create('de_DE', NumberFormatter::DECIMAL); 
$num = "1.234.567,891"; 
echo numfmt_parse($fmt, $num)."\n"; 
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n"; 
?> 

И ожидаемый результат:

1234567.891 
1234567 
1

Это линия, которая форматирует число:

$formatted_price = number_format($price_digits,$decimals, $decimal_point, $thousands_separator); 

И это линии для установки разделителей (, и ,):

$decimal_point = get_option('theme_dec_point'); 
$thousands_separator = get_option('theme_thousands_sep'); 

Вы можете попробовать вернуться к поплавку с этим кодом:

<?php 
function get_option($propertyName) { 
    static $properties = array('theme_dec_point' => '.', 
           'theme_thousands_sep' => ','); 
    return $properties[$propertyName]; 
} 

function formattedprice2float($formatted_price) { 
    $decimal_point = get_option('theme_dec_point'); 
    $thousands_separator = get_option('theme_thousands_sep'); 

    $price_string = str_replace(array($decimal_point, $thousands_separator), 
           array('.', ''), 
           $formatted_price); 
    return is_numeric($price_string) ? (float)$price_string : null; 
} 

// test 
var_dump(formattedprice2float(number_format(100000, 2))); 

Но это предполагает, что параметры не изменяются и, конечно же, выиграл» t восстановить потерянные цифры после десятичной метки. Если первое предположение явно терпит неудачу, цена будет равна нулю.

+0

Спасибо Педро, но код дает эту эрро "Ошибка анализа: синтаксическая ошибка, неожиданный $ end i" –

+0

Привет, Уилсон. Последняя строка не была протестирована, и я добавил неинициализированную переменную, но я считаю, что ошибка не была связана с этим (это означает, что есть дополнительный или отсутствующий разделитель: {, or), или ", или" и т. Д.), Я отредактировал ответ с тестом. Протестируйте его как отдельный файл и скопируйте функцию «formattedprice2float» и используйте его. С уважением. –

+0

Привет, Педро, я снова попытался отредактировать файл с помощью ваших кодов, не уверен, что я делаю правильные вещи или нет. Есть ли способ, которым я могу отправить php-файл любезно –

Смежные вопросы