Jump to content

decimal placement in string


soma56

Recommended Posts

I'm trying to figure out how to place a decimal in the first price of the following:

 

From:

$299 lb / 6.59/kg

 

To:

$2.99 lb / 6.59/kg

 

While I was able to figure this out where the string was simply a numeric value..

 

	// get last two digits of number
	$l2d = substr($price, -2, 2);

	// place decimal before the last two digits of the number
	$price = substr_replace($price, '.', -2, 2) . $l2d;

 

I'm baffled at where to start with this..

Link to comment
https://forums.phpfreaks.com/topic/264515-decimal-placement-in-string/
Share on other sites

Well, first you have to extract the value.

 

<?php

$string = '$299 lb / 6.59/kg';

// find out where ' lb' is
$end = strpos($string, ' lb');

// extract the numbers. we use $end-1 because in this case:
// 4 is the offset of ' lb'. since we start at offset 1 instead
// of offset 0, we will grab an extra character (4, when we only
// want 3)
$price = substr($string, 1, $end-1);

echo $price;
// Outputs 299

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.